設計模式之命令模式——開燈關燈示例

此示例是用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");
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章