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;
    }
  • 相关阅读:
    centos8 防火墙配置增加端口
    linux上搭建maven私服(下)
    linux上搭建maven私服(中)
    项目成本管理中的PV、EV与AC的区别-实例解释
    配置IKE SA的生存周期(华为)
    IKE SA和IPSec SA的区别
    IPsecVPN协商过程-主模式
    Fortigate防火墙常用命令
    飞塔防火墙清除系统密码
    fatal: unable to access ‘https://github xxxxxxxxx的解决方法
  • 原文地址:https://www.cnblogs.com/fourmi/p/12085089.html
Copyright © 2011-2022 走看看