• 命令模式 Command


    1. Client创建一个ConcreteCommand对象并指定他的Receiver对象
    2. 某个Invoker对象存储该ConcreteCommand对象
    3. 该Invoker通过调用Command对象的Execute操作来提交一个请求。若该命令是可撤销的,ConcreteCommand就在执行Execute操作之前存储当前状态以用于取消该命令
    4. ConcreteCommand对象对调用它的Receiver的一些操作以执行该请求
     
    // Command.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <list>
    #include <iostream>
    using namespace std;
    
    class Barbecur{
    public:
        void bakefish(){
            cout<<"开始烤鱼"<<endl;
        }
        void bakemeat(){
            cout<<"开始烤肉"<<endl;
        }
    };
    class Command{
    public:
        Command(Barbecur * p){
            m_p = p;
        }
        virtual void execcommand() = 0;
        virtual ~Command(){}
    protected:
        Barbecur * m_p;
    };
    
    class BakeFishCommand:public Command{
    public:
        BakeFishCommand(Barbecur * p):Command(p){}
        void execcommand(){
            this->m_p->bakefish();
        }
    };
    
    class BakeMeatCommand:public Command{
    public:
        BakeMeatCommand(Barbecur *p):Command(p){}
        void execcommand(){
            this->m_p->bakemeat();
        }
    };
    
    class Waiter{
    public:
        void addcommand(Command * p ){
            m_list.push_back(p);
        }
    
        void cancelcommand(Command * p){
            m_list.remove(p);
        }
    
        void notify(){
            list<Command * >::iterator it;
            for(it = m_list.begin();it!=m_list.end();it++){
                (*it)->execcommand();
            }
        }
    private:
        list<Command *> m_list;
    };
    int main(int argc, char* argv[])
    {
        Barbecur * cooker = new Barbecur;
        Command * pfish = new BakeFishCommand(cooker);
        Command * pmeat = new BakeMeatCommand(cooker);
    
        Waiter * pwaiter = new Waiter;
        pwaiter->addcommand(pfish);
        pwaiter->addcommand(pmeat);
        pwaiter->notify();
    
        pwaiter->cancelcommand(pfish);
        pwaiter->notify();
    
        delete cooker;
        delete pfish;
        delete pmeat;
        delete pwaiter;
        return 0;
    }

     

  • 相关阅读:
    BZOJ4066 简单题(KD-Tree)
    [HAOI2006]受欢迎的牛 tarjan缩点 + 拓扑排序
    [JSOI2007]重要的城市 floyd:最短路计数
    [SDOI2017]新生舞会 0/1分数规划
    [APIO2017]商旅 0/1分数规划
    [HNOI2009]最小圈
    算法——0/1分数规划
    运动员最佳匹配问题 KM算法:带权二分图匹配
    [NOI2015]荷马史诗
    [HAOI2010]计数 数位DP+组合数
  • 原文地址:https://www.cnblogs.com/xiumukediao/p/4656908.html
Copyright © 2020-2023  润新知