设计模式之命令模式Command

将一种请求封装成对象


代码示例:

class ICommand
{
	public:
	virtual void execute() = 0;
};

class switch{
	private:
	ICommand _closedCommand;
	ICommand _openedCommand;
	
	public:
	Switch(ICommand* closedCommand, ICommand* openedCommand)
	{
		_closedCommand = closeCommand;
		_openedCommand = openedCommand;
	}
	
	// close the circuit/power on
	void close()
	{
		_closedCommand->execute();
	}
	
	// open the circuit/power off_type
	void open()
	{
		_openedCommand->execute();
	}
};

class ISwitchable
{
	public:
	virtual void powerOn() = 0;
	virtual void powerOff() = 0;
};


class Light : public ISwitchable
{
	public:
	virtual void powerOn() override
	{
		cout << "The light is on." << endl;
	}
	
	virtual void powerOff() override
	{
		cout << "The light is off." << endl;
	}
};

//The Command for truning on the device - concreteCommand
class CloseSwitchCommand : public ICommand
{
	private:
	ISwitchable _switchable;
	
	public:
	void CloseSwitchCommand(ISwitchable* switchable)
	{
		_switchable = switchable;
	}
	
	virtual void execute() override
	{
		_switchable->powerOn();
	}
};

//The command for turning off the device - concreteCommand
class OpenSwitchCommand : public ICommand
{
	private:
	ISwitchable _switchable;
	
	public:
	OpenSwitchCommand(ISwitchabel* switchable)
	{
		_switchable = switchable;
	}
	
	virtual void execute() override
	{
		_switchable->powerOff();
	}
};


void main(int argc, char** argv)
{
	string argument = argc > 1 ? toUpper(argv[1]) : string();
	ISwitchable* lamp = new Ligth();
	
	//Pass reference to the lamp instance to each command
	ICommand* switchClose = new CloseSwitchCommand(lamp);
	ICommand* switchOpen = new OpenSwitchCommand(lamp);
	
	//Pass reference to instances of the Command objects to the switch
	Switch* pSwitch = new Switch(switchClose, switchOpen);
	
	if(argument == "ON")
	{
		pSwitch->close();
	}
	else if(argument == "OFF")
	{
		pSwitch->open();
	}
	else
	{
		cout << "Argument \"ON\" or \"OFF\" is required." << endl;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值