C++命令模式解析
  TEZNKK3IfmPf 2023年11月15日 35 0
C++


  • 命令模式定义:
    命令模式本质上,就是将命令的调用和执行分开,个人理解,简单的来说,就是每天起来列一天的计划任务,然后在白天的时候,把这些任务给做完,这个就是非常生活化的命令模式,易于理解/

  • 实际工作运用场景,
    在客户端游戏开发过程中,例如游戏中有自动寻路的功能,如果用户点了自动寻路,它在客户端内部的操作是 先将自动寻路的动作加入到命令当中,自动寻路里面有先找到目的地、规划路线、执行走条等一系列命令,这些通过设置命令的调用顺序,执行起来就特别方便,也是使用命令模式的一种方向。

  • 实例代码:

//人的基类=-= 子类实现这些基操
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();
  • 运行结果

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   19天前   26   0   0 C++
  TEZNKK3IfmPf   19天前   22   0   0 指针C++
  TEZNKK3IfmPf   2024年05月31日   23   0   0 算法C++
TEZNKK3IfmPf