命令模式

#include <iostream>
#include <memory>

class Reciever {
public:
    void op1() { std::cout << "In Reciever op1()." << std::endl; }
    void op2() { std::cout << "In Reciever op2()." << std::endl; }
};

class Command {
public:
    virtual void show() = 0;
    void setReciever(std::shared_ptr<Reciever> r) { this->r = r; }
protected:
    std::shared_ptr<Reciever> r = nullptr;
};

class ConcreteCommand1 : public Command {
public:
    void show() override {
        std::cout << "In ConcreteCommand1 show()." << std::endl;
        r->op1();
    }
};

class ConcreteCommand2 : public Command {
public:
    void show() override {
        std::cout << "In ConcreteCommand2 show()." << std::endl;
        r->op2();
    }
};

class Invoker {
public:
    void show() {
        c1->show();
        c2->show();
    }
    void setCommand1(std::shared_ptr<Command> c1) { this->c1 = c1; }
    void setCommand2(std::shared_ptr<Command> c2) { this->c2 = c2; }
private:
    std::shared_ptr<Command> c1;
    std::shared_ptr<Command> c2;
};

int main(int argc, char *argv[]) {
    std::shared_ptr<Reciever> r = std::make_shared<Reciever>();
    std::shared_ptr<Command> c1 = std::make_shared<ConcreteCommand1>();
    std::shared_ptr<Command> c2 = std::make_shared<ConcreteCommand2>();
    c1->setReciever(r);
    c2->setReciever(r);

    Invoker i;
    i.setCommand1(c1);
    i.setCommand2(c2);
    i.show();
    return 1;
}

  

posted @ 2022-02-25 17:59  南乡水  阅读(19)  评论(0编辑  收藏  举报