首页 > 代码库 > 观察者模式

观察者模式

观察者(Observer)模式也称为发布-订阅(publish-subscribe)模式,目标就是通知的发布者(发送通知),观察者就是通知的订阅者(接收通知,被通知)

意图: 定义对象间一对多的依赖关系,使得一个对象被改变,其他对象被更新

 

代码:

#include <iostream>
#include <list>
#include <bitset>
using namespace std;

class Subject;

class Observer
{
public:
    virtual ~Observer() {}
public:
    virtual void update(Subject *s) = 0;
};


class Subject
{
public:
    Subject()
    {
        _observers.clear();
        _state = 0;
    }

public:
    void addObserver(Observer *o)
    {
        _observers.push_back(o);
    }

    void removeObserver(Observer *o)
    {
        _observers.remove(o);
    }

    void notify()
    {
        for (list<Observer*>::iterator it = _observers.begin(); it != _observers.end(); ++it)
        {
            (*it)->update(this);
        }
    }

    void setState(int state)
    {
        if (_state != state)  // 状态改变
        {
            _state = state;
            notify();   // 发送通知
        }
    }
    int getState() const
    {
        return _state;
    }
private:
    list<Observer *> _observers;
    int _state;
};


class BinaryObserver : public Observer
{
public:
    virtual void update(Subject *s)
    {
        bitset<sizeof(int) * 8> bs(s->getState());
        cout << std::dec << s->getState() << "二进制表示: " << bs << endl;
    }
};

class HextObserver : public Observer
{
public:
    virtual void update(Subject *s)
    {
        cout << std::dec << s->getState() << "十六进制表示: " << std::hex << s->getState() << endl;
    }
};

class OctObserver : public Observer
{
public:
    virtual void update(Subject *s)
    {
        cout << std::dec << s->getState() << "八进制表示: " << std::oct << s->getState() << endl;
    }
};

void test()
{
    Subject *sub = new Subject;
    Observer *binaryObserver = new BinaryObserver;  // 二进制格式化数据
    Observer *octObserver = new OctObserver;   // 8进制格式化数据
    Observer *hexObserver = new HextObserver;  // 16进制格式化数据
    sub->addObserver(binaryObserver);
    sub->addObserver(octObserver);
    sub->addObserver(hexObserver);
    sub->setState(8);
    sub->setState(15);
    sub->removeObserver(octObserver);  // 移除8进制格式化数据
    sub->setState(20);
    
    delete sub;
    delete binaryObserver;
    delete octObserver;
    delete hexObserver;

}

int main()
{
    test();
    cin.get();
    return 0;
}

效果:

技术分享

 

观察者模式