C++命令模式(Command)

 C++
时间:

应用场景

认为是命令的地方都可以使用命令模式,比如:

1、GUI 中每一个按钮都是一条命令。

2、模拟 CMD。

Command

  • Command.h
#ifndef _COMMAND_H_
#define _COMMAND_H_

class Reciever;

class Command
{
    public:
        virtual ~Command() {}
        virtual void Excute() = 0;
    protected:
        Command() {}
    private:
};

class ConcreteCommand : public Command
{
    public:
        ConcreteCommand(Reciever* rev);
        ~ConcreteCommand();
        void Excute();
    protected:
    private:
        Reciever* _rev;
};

#endif
  • Command.cpp
#include"Command.h"
#include"Reciever.h"


ConcreteCommand::ConcreteCommand(Reciever* rev) { _rev = rev; }

ConcreteCommand::~ConcreteCommand() { delete _rev; }

void ConcreteCommand::Excute()
{
    _rev->Action();
    cout << "ConcreteCommand......" << endl;
}
  • Invoker.h
#ifndef _INVOKER_H_
#define _INVOKER_H_

class Command;

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

#endif
  • Invoker.cpp
#include"Invoker.h"
#include"Command.h"
#include<iostream>

Invoker::Invoker(Command* cmd)
{
    _cmd = cmd;
}

Invoker::~Invoker()
{
    delete _cmd;
}

void Invoker::Invoke()
{
    _cmd->Excute();
}
  • Reciever.h
#ifndef _RECIEVER_H_
#define _RECIEVER_H_
#include<iostream>
using namespace std;

class Reciever
{
    public:
        Reciever() {}
        ~Reciever() {}
        void Action() { cout << "Reciever action......" << endl; }
    protected:
    private:
};

#endif
  • main.cpp
#include"Command.h"
#include"Invoker.h"
#include"Reciever.h"

#include<iostream>
using namespace std;

int main(int argc, char* argv[])
{
    //接收器
    Reciever* rev = new Reciever();

    Command* cmd = new ConcreteCommand(rev);

    //请求者
    Invoker* inv = new Invoker(cmd);
    inv->Invoke();
    return 0;
}

0 评论