• 命令模式 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;
    }

     

  • 相关阅读:
    django 大体流程
    JavaScript概述
    前端css
    前端基础,加标签
    hashlib模块
    MySQL 了解知识点
    MySQL Navicat 使用
    mysql的基本查询语法及方法 多表查询
    MySQL 外键 一对一 一对多 多对多 复制
    It's likely that neither a Result Type nor a Result Map was specified
  • 原文地址:https://www.cnblogs.com/xiumukediao/p/4656908.html
Copyright © 2020-2023  润新知