命令模式定义:
命令模式本质上,就是将命令的调用和执行分开,个人理解,简单的来说,就是每天起来列一天的计划任务,然后在白天的时候,把这些任务给做完,这个就是非常生活化的命令模式,易于理解/实际工作运用场景,
在客户端游戏开发过程中,例如游戏中有自动寻路的功能,如果用户点了自动寻路,它在客户端内部的操作是 先将自动寻路的动作加入到命令当中,自动寻路里面有先找到目的地、规划路线、执行走条等一系列命令,这些通过设置命令的调用顺序,执行起来就特别方便,也是使用命令模式的一种方向。实例代码:
//人的基类=-= 子类实现这些基操 class IPerson{ public: virtual void Run() = 0; virtual void Eating() = 0; virtual void Sleeping() = 0; virtual void Bash() = 0; }; //执行人 class CRunPerson:public IPerson{ public: virtual void Run() { cout << "执行跑步命令,很快" << endl; } virtual void Bash() { cout << "执行洗澡命令" << endl; } virtual void Sleeping() { cout << "执行睡觉命令" << endl; } virtual void Eating() { cout << "执行吃饭命令" << endl; } }; //执行人 class CEatPerson:public IPerson{ public: virtual void Run() { cout << "执行跑步命令,很快" << endl; } virtual void Bash() { cout << "执行洗澡命令" << endl; } virtual void Sleeping() { cout << "执行睡觉命令" << endl; } virtual void Eating() { cout << "执行吃饭汉堡命令" << endl; } }; class ICommand{ protected: IPerson * m_pPerson; public: ICommand(IPerson *p) { m_pPerson = p; } virtual void ExcuteCommand()=0; }; class CommandRun:public ICommand{ public: CommandRun(IPerson*p):ICommand(p){}; void ExcuteCommand() { m_pPerson->Run(); } }; class CommandEat:public ICommand{ public: CommandEat(IPerson*p):ICommand(p){}; void ExcuteCommand() { m_pPerson->Eating(); } }; class CommandBash:public ICommand{ public: CommandBash(IPerson*p):ICommand(p){}; void ExcuteCommand() { m_pPerson->Bash(); } }; class CommandSleep:public ICommand{ public: CommandSleep(IPerson*p):ICommand(p){}; void ExcuteCommand() { m_pPerson->Sleeping(); } }; //调用者 class CCaller{ private: vector<ICommand*> m_vecCommand; public: void AddCommand(ICommand* iCommand) { m_vecCommand.push_back(iCommand); } void RunCommand() { for (auto it = m_vecCommand.begin();it != m_vecCommand.end();it++) { (*it)->ExcuteCommand(); } } void ReleaseCommand() { for (auto it = m_vecCommand.begin();it != m_vecCommand.end();it++) { delete *it; *it = nullptr; } } };
CEatPerson * eat_ = new CEatPerson(); CRunPerson * rp = new CRunPerson(); CCaller mp; mp.AddCommand(new CommandEat(eat_)); mp.AddCommand(new CommandRun(rp)); mp.AddCommand(new CommandBash(eat_)); mp.RunCommand(); mp.ReleaseCommand();
运行结果