定义:策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
class Light{
public:
void on()
{
cout << "Light on !" << endl;
}
void off()
{
cout << "Light off !" << endl;
}
};
//命令类
class Command{
public:
virtual ~Command(){}
virtual void execute(){}
};
//具体命令类
class LigthOnCommand : public Command
{
public:
LigthOnCommand(Light* lig):light(lig){}
//execute方法
void execute()
{
light->on();
}
private:
Light *light;
};
class LigthOffCommand : public Command{
public:
LigthOffCommand(Light *lig):light(lig){}
//execute方法
void execute()
{
light->off();
}
private:
Light *light;
};
//遥控器类
class RemoteControl{
public:
void SetCommand(Command *cmd)
{
slot = cmd;
}
void buttonOn()
{
slot->execute();
}
private:
Command *slot;
};
int main()
{
RemoteControl lightOnControl;
RemoteControl lightOffControl;
Command *onCommand = new LigthOnCommand(new Light());
Command *offCommand = new LigthOffCommand(new Light());
lightOnControl.SetCommand(onCommand);
lightOffControl.SetCommand(offCommand);
lightOnControl.buttonOn();
lightOffControl.buttonOn();
}