zoukankan      html  css  js  c++  java
  • 设计模式-Command(行为模式) 将一个请求封装到一个Command类中,提供一个处理对象Receiver,将Command由Invoker激活。

    //方式一

    //Reciever.h

    #pragma once
    
    class Reciever{
    public:
        Reciever();
        ~Reciever();
        void Action();
    protected:
    private:
    };

    //Reciever.cpp

    #include"Reciever.h"
    #include<iostream>
    
    Reciever::Reciever(){}
    
    Reciever::~Reciever(){}
    void Reciever::Action()
    {
        std::cout << "Reciever action ..." << std::endl;
    }

    //Command.h

    #pragma once
    
    class Reciever;
    
    class Command{
    public:
        virtual ~Command();
        virtual void Execute() = 0;
    protected:
        Command();
    private:
    };
    
    class ConcreateCommand :public Command
    {
    public:
        ConcreateCommand(Reciever* rec);
        ~ConcreateCommand();
        void Execute();
    protected:
    private:
        Reciever* _rec;
    };

    //Command.cpp

    #include"Command.h"
    #include"Reciever.h"
    #include<iostream>
    
    Command::Command(){}
    Command::~Command(){}
    void Command::Execute(){}
    
    
    ConcreateCommand::ConcreateCommand(Reciever* rec)
    {
        _rec = rec;
    }
    ConcreateCommand::~ConcreateCommand()
    {
        delete this->_rec;
    }
    void ConcreateCommand::Execute()
    {
        _rec->Action();
        std::cout << "ConcreateCommand ..." << std::endl;
    }

    //Invoker.h

    class Command;
    class Invoker
    {
    public:
        Invoker(Command* cmd);
        ~Invoker();
        void Invoke();
    protected:
    private:
        Command* _cmd;
    };

    //Invoker.cpp

    #include"Command.h"
    #include"Invoker.h"
    #include<iostream>
    
    Invoker::Invoker(Command* cmd)
    {
        _cmd = cmd;
    }
    Invoker::~Invoker()
    {
        delete _cmd;
    }
    void Invoker::Invoke()
    {
        _cmd->Execute();
    }

    //main.cpp

    #include"Command.h"
    #include"Invoker.h"
    #include"Reciever.h"
    #include<iostream>
    #include<string>
    
    int main(int args, char* argv)
    {
        Reciever* rec = new Reciever();
        Command* cmd = new ConcreateCommand(rec);
        Invoker* inv = new Invoker(cmd);
        inv->Invoke();
        getchar();
        return 0;
    }
  • 相关阅读:
    JavaScript-4.5 事件大全,事件监听---ShinePans
    SparseArray具体解释,我说SparseArray,你说要!
    Spark Core源代码分析: RDD基础
    我的 Android 开发实战经验总结
    物联网的一种參考架构
    【LeetCode】 Rotate List 循环链表
    放苹果(整数划分变形题 水)poj1664
    ps白平衡
    jfinal对象封装Record原理
    ps通道混合器
  • 原文地址:https://www.cnblogs.com/fourmi/p/12085089.html
Copyright © 2011-2022 走看看