设计模式之命令模式——开灯关灯示例

此示例是用C++写的对灯颜色的控制,如开红灯,蓝灯等,如控制其它的设备也可像红灯,蓝灯一样封装好后进行SetCommand,仅供参考。

#include<iostream>
using namespace std;

class Command
{
public:
	Command() { };
	~Command() { };
	virtual void Execute() {};

private:

};
class Light
{
public:
	Light() { };
	~Light() { };
	virtual void On() {	};
	virtual void Off() { };
private:
};
class RedLight :public Light
{
public:
	RedLight() {};
	~RedLight() {};
	 void On()
	{
		cout << "Red ligtht on\n" << endl;
	}
	 void Off()
	{
		cout << "Red ligtht off\n" << endl;
	}
public:
	int n = 3;
};

class BlueLight :public Light
{
public:
	BlueLight() {};
	~BlueLight() {};
	 void On()
	{
		cout << "Blue ligtht on\n" << endl;
	}
	 void Off()
	{
		cout << "Blue ligtht off\n" << endl;
	}

};
class LightOnCommand:public Command
{
public:
	LightOnCommand() {};
	~LightOnCommand(){ };
	void SetLight(Light *light)
	{
		m_light = light;
	}
	void Execute()
	{
		m_light->On();
	}
private:
	Light *m_light;
};
class LightOffCommand :public Command
{
public:
	LightOffCommand() {};
	~LightOffCommand() { };
	void SetLight(Light *light)
	{
		m_light = light;
	}
	virtual void Execute()
	{
		m_light->Off();
	}
private:
	Light *m_light;

};


class SimpleRemoteControl
{
public:
	SimpleRemoteControl() { };
	~SimpleRemoteControl() { };
	void SetCommand(Command *command)
	{
		m_slot = command;
	}
	void ButtonWasPressed()
	{
		m_slot->Execute();
	}
private:
	Command *m_slot;
};
#include<vector>
void main()
{
	
	


	LightOnCommand *lightOnCommand = new LightOnCommand;
	LightOffCommand *lightOffCommand = new LightOffCommand;
	SimpleRemoteControl remoteControl;
	Light *pLigtht = new RedLight();

	lightOnCommand->SetLight(pLigtht);
	lightOffCommand->SetLight(pLigtht);

	
	remoteControl.SetCommand(lightOnCommand);
	remoteControl.ButtonWasPressed();
	remoteControl.SetCommand(lightOffCommand);
	remoteControl.ButtonWasPressed();

	delete pLigtht;
	pLigtht = NULL;

	pLigtht = new BlueLight();
	lightOnCommand->SetLight(pLigtht);
	lightOffCommand->SetLight(pLigtht);
	remoteControl.SetCommand(lightOnCommand);
	remoteControl.ButtonWasPressed();
	remoteControl.SetCommand(lightOffCommand);
	remoteControl.ButtonWasPressed();

	delete lightOnCommand;
	lightOnCommand = NULL;
	delete lightOffCommand;
	lightOffCommand = NULL;
	system("pause");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值