BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Design Patterns - Observer Pattern

Patterns.png




Bookmark and Share





bogotobogo.com site search:

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.




observer_pattern

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:

  1. 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); }
  2. Each subject can have many observers.
    class Subject 
    { 
    public: 
     Subject() {}; 
     ~Subject() {}; 
     void Attach(Observer*); 
     void Detach(Observer*); 
     void Notify(); 
    private: 
     vector<Observer*> _observers; 
    }; 
    
  3. 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;   
    };
    
  4. 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); 
    }
    
  5. 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]; 
    }; 
    
  6. 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); 
    } 
    
  7. The two objects of Observer Pattern are loosely coupled, they can interact but with little knowledge of each other.



2nd Example of Observer Pattern

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.



Variations

There are some variation of the Observer pattern.

  1. 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.

  2. 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

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong





List of Design Patterns



Introduction

Abstract Factory Pattern

Adapter Pattern

Bridge Pattern

Chain of Responsibility

Command Pattern

Composite Pattern

Decorator Pattern

Delegation

Dependency Injection(DI) and Inversion of Control(IoC)

Façade Pattern

Factory Method

Model View Controller (MVC) Pattern

Observer Pattern

Prototype Pattern

Proxy Pattern

Singleton Pattern

Strategy Pattern

Template Method Pattern

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master