观察者模式

#include <iostream>
#include <list>
#include <memory>

class AbstractObserver {
public:
    virtual void update(std::string msg) = 0;
};

class AbstractSubject {
public:
    virtual void attach(std::shared_ptr<AbstractObserver> o) = 0;
    virtual void detach(std::shared_ptr<AbstractObserver> o) = 0;
    virtual void notify() = 0;
};

class ConcreteObserver1 : public AbstractObserver {
public:
    void update(std::string msg) override {
        msg_ = msg;
        std::cout << "In ConcreteObserver1 update(). The msg is " << msg_ << std::endl;
    }
    void show() { std::cout << "In ConcreteObserver1 show(). The msg is " << msg_ << std::endl; }
private:
    std::string msg_ = "";
};

class ConcreteObserver2 : public AbstractObserver {
public:
    void update(std::string msg) override {
        msg_ = msg;
        std::cout << "In ConcreteObserver2 update(). The msg is " << msg_ << std::endl;
    }
    void show() { std::cout << "In ConcreteObserver2 show(). The msg is " << msg_ << std::endl; }
private:
    std::string msg_ = "";
};

class ConcreteSubject : public AbstractSubject {
public:
    void attach(std::shared_ptr<AbstractObserver> o) override { lo.emplace_back(o); }
    void detach(std::shared_ptr<AbstractObserver> o) override { lo.remove(o); }
    void notify() override {
        for (const auto& o : lo) {
            o->update(msg_);
        }
    }
    void setMsg(std::string msg) {
        this->msg_ = msg;
        notify();
    }
private:
    std::list<std::shared_ptr<AbstractObserver>> lo;
    std::string msg_ = "";
};

int main(int argc, char *argv[]) {
    std::shared_ptr<ConcreteObserver1> ab1 = std::make_shared<ConcreteObserver1>();
    std::shared_ptr<ConcreteObserver2> ab2 = std::make_shared<ConcreteObserver2>();
    std::shared_ptr<ConcreteSubject> cs = std::make_shared<ConcreteSubject>();
    cs->attach(ab1);
    cs->attach(ab2);
    ab1->show();
    ab2->show();
    cs->setMsg("msg1");
    ab1->show();
    ab2->show();
    cs->detach(ab1);
    cs->setMsg("msg2");
    ab1->show();
    ab2->show();
    return 1;
}

  

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