美文网首页设计模式C++实现笔记
OBSERVER观察者模式(行为模式)

OBSERVER观察者模式(行为模式)

作者: lixin_karl | 来源:发表于2019-03-14 17:35 被阅读0次

介绍

定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。

参与者

  • Subject 目标
  • Observer 观察者
  • ConcreteSubject 目标具体实现
  • ConcreteObserver 观察者具体实现

实现代码

class Subject;
class Observer{
public:
    virtual void Update() = 0;
};
class Subject{
public:
    virtual void AddObserver(Observer* o)=0;
    virtual void DelObserver(Observer* o)=0;
    virtual void setState(int a) = 0;
    virtual int getState() = 0;

};
class ConcreteSubject : public Subject {
public:
    void AddObserver(Observer* o) override
    {
        l.push_back(o);
    }
    void DelObserver(Observer* o) override
    {
        l.remove(o);
    }
    void setState(int a)
    {
        state = a;
        NotifyAll();
    }
    int getState() override
    {
        return state;
    }
private:
    void NotifyAll()
    {
        for(auto item : l)
        {
            item->Update();
        }
    }
    int state = 0;
    std::list<Observer *> l;
};

class ObserverA:public  Observer{
public:
    explicit ObserverA(Subject *subject1)
    {
        subject = subject1;
        this->subject->AddObserver(this);
    }
    void Update() override
    {
        std::cout<<"Update A After Subject State Changed To "<<subject->getState()<<std::endl;
    }

private:
    Subject *subject;
};
class ObserverB:public  Observer{
public:
    explicit ObserverB(Subject *subject1)
    {
        subject = subject1;
        this->subject->AddObserver(this);
    }
    void Update() override
    {
        std::cout<<"Update B After Subject State Changed To "<<subject->getState()<<std::endl;
    }
private:
    Subject *subject;
};

int main()
{
    Subject *subject = new ConcreteSubject();
    Observer *a = new ObserverA(subject);
    Observer *b = new ObserverB(subject);

    subject->setState(22);
    std::cout<<"------------------------------------------"<<std::endl;
    subject->setState(35);
    return 0;
}

输出结果

Update A After Subject State Changed To 22
Update B After Subject State Changed To 22
------------------------------------------
Update A After Subject State Changed To 35
Update B After Subject State Changed To 35

特点

  • 观察者和被观察者是抽象耦合的
  • 建立一套触发机制
  • 如果一个被观察者对象有很多的直接和间接的观察者的话,将所有的观察者都通知到会花费很多时间
  • 如果在观察者和观察目标之间有循环依赖的话,观察目标会触发它们之间进行循环调用,可能导致系统崩溃

参考

相关文章

网友评论

    本文标题:OBSERVER观察者模式(行为模式)

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