中介者模式

#include <iostream>
#include <memory>

class Mediator {
public:
    virtual void Notify(std::string Msg) = 0;
};

class BaseComponent {
public:
    virtual void opt() = 0;
    virtual void respond() = 0;
protected:
    std::shared_ptr<Mediator> m = nullptr;
};

class ConcreteComponet1 : public BaseComponent {
public:
    void opt() override {
        std::cout << "In ConcreteComponet1 opt show()." << std::endl;
        if(m) { m->Notify(std::string("One")); }
    }
    void respond() override { std::cout << "In ConcreteComponet1 respond()." << std::endl; }
    void setMediator(std::shared_ptr<Mediator> m) { this->m = m; }
};

class ConcreteComponet2 : public BaseComponent {
public:
    void opt() override {
        std::cout << "In ConcreteComponet2 opt()." << std::endl;
        if(m) { m->Notify("Two"); }
    }
    void respond() override { std::cout << "In ConcreteComponet2 respond()." << std::endl; }
    void setMediator(std::shared_ptr<Mediator> m) { this->m = m; }
};

class ConcreteMediator : public Mediator {
public:
    ConcreteMediator(std::shared_ptr<ConcreteComponet1> b1, std::shared_ptr<ConcreteComponet2> b2) : b1(b1), b2(b2) { }
    void Notify(std::string Msg) override {
        if (Msg == "One") { b2->respond(); }
        if (Msg == "Two") { b1->respond(); }
    }
    void setComponent(std::shared_ptr<ConcreteComponet1> b1, std::shared_ptr<ConcreteComponet2> b2){
        this->b1 = b1;
        this->b2 = b2;
    }
private:
    std::shared_ptr<ConcreteComponet1> b1 = nullptr;
    std::shared_ptr<ConcreteComponet2> b2 = nullptr;
};

int main(int argc, char *argv[]) {
    std::shared_ptr<ConcreteComponet1> b1 = std::make_shared<ConcreteComponet1>();
    std::shared_ptr<ConcreteComponet2> b2 = std::make_shared<ConcreteComponet2>();
    std::shared_ptr<ConcreteMediator> cm = std::make_shared<ConcreteMediator>(b1, b2);
    b1->setMediator(cm);
    b2->setMediator(cm);

    b1->opt();
    b2->opt();
    return 1;
}

  

posted @ 2022-02-25 18:13  南乡水  阅读(20)  评论(0编辑  收藏  举报