Observer模式实践

  Observer 模式在实践中的应用场景:

  为 Point 类设计一个数据绑定机制,当其坐标 x 或 y 被更改时,可以通知外界其更改的过程。将更改过程打印在控制台上。考虑使用松耦合设计。

  代码:

#include <list>
#include <iostream>

using namespace std;

struct Observer;
struct Subject
{
    virtual void attach(Observer*) = 0;
    virtual void detach(Observer*) = 0;
    virtual void notify() = 0;
    virtual int getX() = 0;
    virtual int getY() = 0;

    list<Observer*> _observer;
};

struct Observer
{
    virtual void update(Subject*) = 0;
};

struct ConsoleObserver : public Observer {
    virtual void update(Subject *subject)
    {
        cout << subject->getX() << " " << subject->getY() << endl;
    }
};

class Point : public Subject{
    int _x;
    int _y;

public:
    virtual void attach(Observer* o)
    {
        this->_observer.push_back(o);
    }

    virtual void detach(Observer* o)
    {
        this->_observer.remove(o);
    }
    
    virtual void notify() {
        for (auto e : _observer)
            e->update(this);
    }

    Point(int x, int y) : _x(x), _y(y) {}

    void setX(int x)
    {
        this->_x = x;
        this->notify();
    }

    void setY(int y)
    {
        this->_y = y;
        this->notify();
    }

    int getX()
    {
        return this->_x;
    }

    int getY()
    {
        return this->_y;
    }
};

int main()
{
    Point po(1, 2);


    //绑定
    ConsoleObserver co;
    po.attach(&co);


    //值的每一次变化,都会引起控制台打印
    po.setX(3);
    po.setY(4);

    return 0;
}

 

posted @ 2015-12-15 21:52  健康平安快乐  阅读(309)  评论(0编辑  收藏  举报