Command 模式C++ 代码

本文介绍了一个基于命令模式的设计实例,定义了多个具体命令类(Command1、Command2、Command3),并通过一个排除类来管理这些命令的执行。该示例展示了如何通过面向对象的方式组织不同的操作,并提供了一种将请求封装为对象的方法。
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class CommandBase
{
    public:
	virtual void run()=0;
	
    private:
};

class Command1:public CommandBase
{
    public:
	Command1(string strName):m_strName(strName){};
	void run()
	{
        cout<<m_strName<<endl;
	}
	
	private:
	string m_strName;
};
class Command2:public CommandBase
{
    public:
	Command2(string strName):m_strName(strName){};
	void run()
	{
        cout<<m_strName<<endl;
	}
	
	private:
	string m_strName;
};

class Command3:public CommandBase
{
    public:
	Command3(string strName):m_strName(strName){};
	void run()
	{
        cout<<m_strName<<endl;
	}
	
	private:
	string m_strName;
};

class Exclude
{
   public:
    void add(CommandBase& Command)
    {
	    m_vetorCommand.push_back(&Command);
	}
	void run()
	{
        vector <CommandBase*>::iterator Itr = m_vetorCommand.begin();
		while(Itr != m_vetorCommand.end())
		{
            (*Itr++)->run();
		}
	}
	
   private:
   	vector <CommandBase*> m_vetorCommand;
   	static Exclude m_cExclude; 
};

int main()
{
    Command1 cCommand1("cmd1");
    Command2 cCommand2("cmd2");
    Command3 cCommand3("cmd3");

   Exclude cExclude;
   cExclude.add(cCommand1);
   cExclude.add(cCommand2);
   cExclude.add(cCommand3);
   cExclude.run();

   while(1);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值