笔记:Gof设计模式--Observer

来源:互联网 发布:iphone保护壳 知乎 编辑:程序博客网 时间:2024/06/08 12:11

1、意图

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

2、适应性

  Use the Observer pattern in any of the following situations:

  •  When an abstraction has two aspects, one dependent on the other.Encapsulating these aspects in separate objects lets you vary and reuse them independently.
  •  When a change to one object requires changing others, and you don't know how many objects need to be changed.
  •  When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled.
 

3、结构

 

 

 

 

 

4、示例代码

  An abstract class defines the Observer interface:

class Subject;  class Observer { public:     virtual ~ Observer();     virtual void Update(Subject* theChangedSubject) = 0; protected:     Observer(); }; 

 

  Similarly, an abstract class defines the Subject interface:

class Subject { public:     virtual ~Subject();     virtual void Attach(Observer*);     virtual void Detach(Observer*);     virtual void Notify(); protected:     Subject(); private:     List<Observer*> *_observers; }; void Subject::Attach (Observer* o) {            _observers->Append(o);    }  void Subject::Detach (Observer* o) {            _observers->Remove(o);    }  void Subject::Notify () {     ListIterator<Observer*> i(_observers);     for (i.First(); !i.IsDone(); i.Next()) {        i.CurrentItem()->Update(this);     } } 


 

 ClockTimer is a concrete subject for storing andmaintaining the time of day. It notifies its observers every second.ClockTimer provides the interface for retrieving individualtime units such as the hour, minute, and second.

class ClockTimer : public Subject { public:     ClockTimer();     virtual int GetHour();     virtual int GetMinute();     virtual int GetSecond();     void Tick(); }; void ClockTimer::Tick () {     // update internal time-keeping state     // ...     Notify(); } 


 

 

class DigitalClock: public Widget, public Observer {     public:             DigitalClock(ClockTimer*);     virtual ~DigitalClock();     virtual void Update(Subject*);     // overrides Observer operation     virtual void Draw();     // overrides Widget operation;     // defines how to draw the digital clock private:     ClockTimer* _subject; };  DigitalClock::DigitalClock (ClockTimer* s) {     _subject = s;     _subject->Attach(this); }  DigitalClock:: DigitalClock () {     _subject->Detach(this); }void DigitalClock::Update (Subject* theChangedSubject) {     if (theChangedSubject == _subject) {         Draw();     } }  void DigitalClock::Draw () {     // get the new values from the subject      int hour = _subject->GetHour();     int minute = _subject->GetMinute();     // etc.      // draw the digital clock }