Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1715790
  • 博文数量: 177
  • 博客积分: 9416
  • 博客等级: 中将
  • 技术积分: 2513
  • 用 户 组: 普通用户
  • 注册时间: 2006-01-06 16:08
文章分类

全部博文(177)

文章存档

2013年(4)

2012年(13)

2011年(9)

2010年(71)

2009年(12)

2008年(11)

2007年(32)

2006年(25)

分类:

2010-01-12 15:02:30

Observer is one of the simplest design patterns. It can be understood as callback function. The definition in GOF's book is:

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

My understanding is: Observer pattern is a way to notify a series of objects (observers) that something happened in subject object. The subject object "generates" the event and observer objects "receive" it. For example, when mouse click is captured, OS dispatches the event to the window, which in turn calls the event handler of all registered observers. Picture below illustrates the class diagram of this pattern:

class Subject
{
public:
    void Add(IObserver* obs);
    void Remove(IObserver* obs);
    void Notify();

private:

    list obs_list;
};


void Subject::Notify()
{
    for (Observer* t = obs_list.begin(); t != obs_list.end(); t++)
        t->Update();
}


阅读(1159) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~