command模式

作者: 老练子丶2017 | 来源:发表于2017-11-24 14:32 被阅读0次

    不同的命令产生不同的结果,由invoke发放命令

    command.h

    #ifndef _COMMAND_H

    #define _COMMAND_H

    #include <iostream>

    using namespace std;

    class Receiver

    {

    public:

    Receiver() {

    }

    ~Receiver() {

    }

    void Cmd1() {

    cout << "cmd1" << endl;

    }

    void Cmd2() {

    cout << "cmd2" << endl;

    }

    };

    class Command

    {

    public:

    virtual ~Command() {

    }

    virtual void Excute()=0;

    protected:

    Command() {

    }

    };

    class ConcreteCommand1 : public Command

    {

    public:

    ConcreteCommand1() {

    rece_ = new Receiver;

    }

    void Excute() {

    rece_->Cmd1();

    }

    private:

    Receiver* rece_;

    };

    class ConcreteCommand2 : public Command

    {

    public:

    ConcreteCommand2() {

    rece_ = new Receiver;

    }

    void Excute() {

    rece_->Cmd2();

    }

    private:

    Receiver* rece_;

    };

    class Invoker

    {

    public:

    Invoker(Command* cmd) : _cmd(cmd) {

    }

    ~Invoker() {

    }

    void invoke() {

    _cmd->Excute();

    }

    private:

    Command* _cmd;

    };

    #endif // _COMMAND_H

    command.cpp

    #include "command.h"

    int main()

    {

    Command* cmd = new ConcreteCommand1;

    Invoker* invoker1 = new Invoker(cmd);

    invoker1->invoke();

    return 0;

    }

    编译:make command

    相关文章

      网友评论

        本文标题:command模式

        本文链接:https://www.haomeiwen.com/subject/wcffbxtx.html