Design Patterns
- Observer Pattern
Observer Pattern's intent is to define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
The subject and observers define the one-to-many relationship. The observers are dependent on the subject such that when the subject's state changes, the observers get notified. Depending on the notification, the observers may also be updated with new values.
Here is the example from the book "Design Patterns" by Gamma.
#include <iostream> #include <vector> #include <time.h> #include <sys/types.h> #include <sys/timeb.h> #include <string.h> using namespace std ; class Subject; class Observer { public: Observer() {}; ~Observer() {}; virtual void Update(Subject* theChangeSubject) = 0; }; class Subject { public: Subject() {}; virtual ~Subject() {}; virtual void Attach(Observer*); virtual void Detach(Observer*); virtual void Notify(); private: vector<Observer*> _observers; }; void Subject::Attach (Observer* o) { _observers.push_back(o); } void Subject::Detach (Observer* o) { int count = _observers.size(); int i; for (i = 0; i < count; i++) { if(_observers[i] == o) break; } if(i < count) _observers.erase(_observers.begin() + i); } void Subject::Notify () { int count = _observers.size(); for (int i = 0; i < count; i++) (_observers[i])->Update(this); } class ClockTimer : public Subject { public: ClockTimer() { _strtime( tmpbuf ); }; int GetHour(); int GetMinute(); int GetSecond(); void Tick(); private: char tmpbuf[128]; }; /* Set time zone from TZ environment variable. If TZ is not set, * the operating system is queried to obtain the default value * for the variable. */ void ClockTimer::Tick() { _tzset(); // Obtain operating system-style time. _strtime( tmpbuf ); Notify(); } int ClockTimer::GetHour() { char timebuf[128]; strncpy(timebuf, tmpbuf, 2); timebuf[2] = NULL; return atoi(timebuf); } int ClockTimer::GetMinute() { char timebuf[128]; strncpy(timebuf, tmpbuf+3, 2); timebuf[2] = NULL; return atoi(timebuf); } int ClockTimer::GetSecond() { char timebuf[128]; strncpy(timebuf, tmpbuf+6, 2); timebuf[2] = NULL; return atoi(timebuf); } class DigitalClock: public Observer { public: DigitalClock(ClockTimer *); ~DigitalClock(); void Update(Subject *); void Draw(); 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 () { int hour = _subject->GetHour(); int minute = _subject->GetMinute(); int second = _subject->GetSecond(); cout << "Digital time is " << hour << ":" << minute << ":" << second << endl; } class AnalogClock: public Observer { public: AnalogClock(ClockTimer *); ~AnalogClock(); void Update(Subject *); void Draw(); private: ClockTimer *_subject; }; AnalogClock::AnalogClock (ClockTimer *s) { _subject = s; _subject->Attach(this); } AnalogClock::~AnalogClock () { _subject->Detach(this); } void AnalogClock::Update (Subject *theChangedSubject) { if(theChangedSubject == _subject) Draw(); } void AnalogClock::Draw () { int hour = _subject->GetHour(); int minute = _subject->GetMinute(); int second = _subject->GetSecond(); cout << "Analog time is " << hour << ":" << minute << ":" << second << endl; } int main(void) { ClockTimer timer; DigitalClock digitalClock(&timer;); AnalogClock analogClock(&timer;); timer.Tick(); return 0; }
Output:
Digital time is 14:41:36 Analog time is 14:41:36
Here are the summary of the pattern:
- Objects (DigitalClock or AnalogClock object) use the Subject interfaces (Attach() or Detach()) either to subscribe (register) as observers or unsubscribe (remove) themselves from being observers.
DigitalClock::DigitalClock (ClockTimer *s) { _subject = s; _subject->Attach(this); }
DigitalClock::~DigitalClock () { _subject->Detach(this); } - Each subject can have many observers.
class Subject { public: Subject() {}; ~Subject() {}; void Attach(Observer*); void Detach(Observer*); void Notify(); private: vector<Observer*> _observers; };
- All observers need to implement the Observer interface. This interface just has one method, Update(), that gets called when the Subject's state changes.
class AnalogClock: public Observer { public: AnalogClock(ClockTimer *); ~AnalogClock(); void Update(Subject *); void Draw(); private: ClockTimer *_subject; };
- In addition to the attach() and detach() methods, the concrete subject implements a Notify() method that is used to update all the current observers whenever state changes. But in this case, all of them are done in the parent class, Subject.
void Subject::Attach (Observer* o) { _observers.push_back(o); } void Subject::Detach(Observer* o) { int count = _observers.size(); int i; for (i = 0; i < count; i++) { if(_observers[i] == o) break; } if(i < count) _observers.erase(_observers.begin() + i); } void Subject::Notify() { int count = _observers.size(); for (int i = 0; i < count; i++) (_observers[i])->Update(this); }
- The Concrete object may also have methods for setting and getting its state.
class ClockTimer : public Subject { public: ClockTimer() { _strtime( tmpbuf ); }; int GetHour(); int GetMinute(); int GetSecond(); void Tick(); private: char tmpbuf[128]; };
- Concrete observers can be any class that implements the Observer interface. Each observer subscribe (register) with a concrete subject to receive update.
DigitalClock::DigitalClock (ClockTimer *s) { _subject = s; _subject->Attach(this); }
- The two objects of Observer Pattern are loosely coupled, they can interact but with little knowledge of each other.
The following example is not much different from the previous one. The important point to notice is that the MySubject class has not compile-time dependency on the MyObserver class. The relationship between the two classes is dynamically created at run time.
#include <iostream> #include <vector> #include <string> class ObserverInterface { public: virtual ~ObserverInterface() {} virtual void update(int message) = 0; }; class SubjectInterface { public: virtual ~SubjectInterface(); virtual void subscribe(ObserverInterface *); virtual void unsubscribe (ObserverInterface *); virtual void notify(int message); private: std::vector<ObserverInterface *> mObservers; }; SubjectInterface::~SubjectInterface() {} void SubjectInterface::subscribe(ObserverInterface *observer) { mObservers.push_back(observer); } void SubjectInterface::unsubscribe(ObserverInterface *observer) { int count = mObservers.size(); int i; for (i = 0; i < count; i++) { if(mObservers[i] == 0) break; } if(i < count) mObservers.erase(mObservers.begin() + i); } void SubjectInterface::notify(int msg) { int count = mObservers.size(); for (int i = 0; i < count; i++) (mObservers[i])->update(msg); } class MySubject : public SubjectInterface { public: enum Message {ADD, REMOVE}; }; class MyObserver : public ObserverInterface { public: explicit MyObserver(const std::string &str;) : name(str) {} void update(int message) { std::cout << name << " Got message " << message << std::endl; } private: std::string name; }; int main() { MyObserver observerA("observerA"); MyObserver observerB("observerB"); MyObserver observerC("observerC"); MySubject subject; subject.subscribe(&observerA;); subject.subscribe(&observerB;); subject.unsubscribe(&observerB;); subject.subscribe(&observerC;); subject.notify(MySubject::ADD); subject.notify(MySubject::REMOVE); return 0; }
Output:
observerA Got message 0 observerB Got message 0 observerC Got message 0 observerA Got message 1 observerB Got message 1 observerC Got message 1
The calls to subject.notify() cause the subject to traverse its list of observers that have been subscribed and the call to (mObservers[i])->update(msg) method for each of them.
There may be a small performance hit due to iterating through a list of observers before making the virtual function call. However, the cost is minimal when compared to the benefits of reduced coupling and increased code reuse.
There are some variation of the Observer pattern.
- Signal and Slots
Signals and slots is a language construct introduced in Qt, which makes it easy to implement the Observer pattern while avoiding boilerplate code. The concept is that controls (also known as widgets) can send signals containing event information which can be received by other controls using special functions known as slots. The slot in Qt must be a class member declared as such.
The signal/slot system fits well with the way Graphical User Interfaces are designed. Similarly, the signal/slot system can be used for asynchronous I/O (including sockets, pipes, serial devices, etc.) event notification or to associate timeout events with appropriate object instances and methods or functions. No registration/deregistration/invocation code need be written, because Qt's Meta Object Compiler (MOC) automatically generates the needed infrastructure.
- C# Events and Delegates
The C# language also supports a similar construct although with a different terminology and syntax: events play the role of signals, and delegates are the slots. Additionally, a delegate can be a local variable, much like a function pointer, while a slot in Qt must be a class member declared as such.
For more information about C# Delegate, go to C# Tutorial - Delegates
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization