观察者模式(observe method)

前言:虚函数、继承、模板函数、模板类基础知识

点击查看代码
#include<iostream>
#include<memory>
#include<list>
using namespace std;

class Observer;

//抽象目标
class Subject{
public:
    virtual void Attach(Observer*) = 0;
    virtual void Detach(Observer*) = 0;
    virtual void Notify() = 0;

};
//抽象观察者
class Observer {
public:
    virtual void Update(int) = 0;
};
//具体目标
class ConcreteSubject : public Subject{
public:
    virtual void Attach(Observer* observer) {
        if (!observer) {
            return;
        }
        _observers.push_back(observer);
    }
    virtual void Detach(Observer* observer) {
        if (!observer) {
            return;
        }
        _observers.remove(observer);
    }
    virtual void Notify() {
        list<Observer *>::iterator it;
        for(it = _observers.begin(); it != _observers.end(); ++it) {
            (*it)->Update(_state);
        }
    }
    void SetState(int state) {
        _state = state;
    }
private:
    list<Observer *> _observers;
    int _state;
};
//具体观察者
class ConcreteObserver : public Observer{
public:
    ConcreteObserver(Subject* masterSubject) : _masterSubject(masterSubject)
    {}
    virtual void Update(int val) {
        cout << "the state of subject is " << val<< endl;
    }
private:
    Subject* _masterSubject;
};
int main() {
    // 创建目标,创建观察者,添加观察者,设置状态,通知观察者
    ConcreteSubject subject;
    shared_ptr<ConcreteObserver> obj1 =
        make_shared<ConcreteObserver> (&subject);
    subject.Attach(obj1.get());

    shared_ptr<ConcreteObserver> obj2 =
        make_shared<ConcreteObserver> (&subject);
    subject.Attach(obj2.get());

    subject.SetState(5);
    subject.Notify();
    // 移除观察者,设置状态,通知观察者
    subject.Detach(obj2.get());

    subject.SetState(999);
    subject.Notify();

    return 0;
}

posted @ 2022-06-19 01:27  locker_10086  阅读(28)  评论(0编辑  收藏  举报