设计模式之观察者

来源:互联网 发布:数据挖掘 常用模型 编辑:程序博客网 时间:2024/04/26 05:32

设计模式之观察者
参考文章:
https://sourcemaking.com/design_patterns/observer

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
定义一个一对多的对象间关系,当一个对象发生改变的时候,所有依赖他的对象都将被通知并自动更新。
Encapsulate the core (or common or engine) components in a Subject abstraction, and the variable (or optional or user interface) components in an Observer hierarchy.
将核心的部分封装到一个Subject abstraction中,将易变的部分封装到一个Observer hierarchy中。

The “View” part of Model-View-Controller.
MVC中的视图部分。

===========================================================

1.用一个抽象出来的subject使独立(independent)的功能模型化。
2.用观察者(observer)的层次等级,模型化依赖(dependent)功能。
3.Subject 只和Observer 的基类产生关联。
4.Observers 用Subject注册自己。
5.Subject 要向所有注册了的Observers作通知。
6.Observers 从Subject“拉”(pull)他们需要的信息。
7.Client 配置Observers的数量和类型。

#include <iostream>#include <vector>using namespace std;class Subject {    // 1. "independent" functionality    vector < class Observer * > views; // 3. Coupled only to "interface"    int value;  public:    void attach(Observer *obs) {        views.push_back(obs);    }    void setVal(int val) {        value = val;        notify();    }    int getVal() {        return value;    }    void notify();};class Observer {    // 2. "dependent" functionality    Subject *model;    int denom;  public:    Observer(Subject *mod, int div) {        model = mod;        denom = div;        // 4. Observers register themselves with the Subject        model->attach(this);    }    virtual void update() = 0;  protected:    Subject *getSubject() {        return model;    }    int getDivisor() {        return denom;    }};void Subject::notify() {  // 5. Publisher broadcasts  for (int i = 0; i < views.size(); i++)    views[i]->update();}class DivObserver: public Observer {  public:    DivObserver(Subject *mod, int div): Observer(mod, div){}    void update() {        // 6. "Pull" information of interest        int v = getSubject()->getVal(), d = getDivisor();        cout << v << " div " << d << " is " << v / d << '\n';    }};class ModObserver: public Observer {  public:    ModObserver(Subject *mod, int div): Observer(mod, div){}    void update() {        int v = getSubject()->getVal(), d = getDivisor();        cout << v << " mod " << d << " is " << v % d << '\n';    }};int main() {  Subject subj;  DivObserver divObs1(&subj, 4); // 7. Client configures the number and  DivObserver divObs2(&subj, 3); //    type of Observers  ModObserver modObs3(&subj, 3);  subj.setVal(14);}

Output

14 div 4 is 3
14 div 3 is 4
14 mod 3 is 2

0 0
原创粉丝点击