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