• 设计模式-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;
    }
  • 相关阅读:
    埋点
    go 搭建web服务
    go的常见操作
    Zeus资源调度系统介绍
    支付系统中热点账户的性能问题
    redis
    集成Spring-Boot与gRPC,grpc-spring-boot-starter
    Spring Cloud灰度发布之Nepxion Discovery
    Spring Cloud Stream
    通过消息总线Spring Cloud Bus实现配置文件刷新(使用Kafka或RocketMQ)
  • 原文地址:https://www.cnblogs.com/fourmi/p/12085089.html
Copyright © 2020-2023  润新知