Solved

Observer Design Pattern in C++

Posted on 2010-09-22
5
1,280 Views
Last Modified: 2013-11-13
I need to learn the basics of Observer Design Pattern. I went through the following sites

http://sourcemaking.com/design_patterns/observer/cpp/3
http://www.answers.com/topic/observer-pattern#C.2B.2B

I could not understand much on the technical side i.e. the implementation. I request experts to provide simple examples.
0
Comment
Question by:sukhoi35
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 40

Expert Comment

by:evilrix
ID: 33735472
Have you taken the look on Wikipedia?
http://en.wikipedia.org/wiki/Observer_pattern

The explanation and examples there are quite simple to follow.
0
 
LVL 12

Accepted Solution

by:
w00te earned 400 total points
ID: 33736155
Well, you should really read on the web to learn about it more like the wiki article from above, but here's a fully functional example written as one source file.  It has observer & subject interfaces and classes implementing them. There's a main showing how they're used and its well commented.

Hope it helps (I did it for learning way back so it should be simple and to the point);

-w00te
#include <iostream>
#include <list>
#include <string>
#include <algorithm>

//===========================================================
//	Define the OObserver Class 
//		-Constructor calling attach() method left until after Subject definition.
//===========================================================

class OSubject;
class OObserver
{
	private:
		OSubject* subject_;
	
	public:
		OObserver(OSubject* subject);
		virtual void update()=0;
};

//===========================================================
//	Define the OSubject Class 
//		-attach() method left until after Subject definition.
//===========================================================

class OSubject 
{
	private:
		std::list<OObserver*> observers_;

	public:
		void attach(OObserver* obs) { observers_.push_back(obs); }
		void detach(OObserver* obs) 
		{ 
			std::list<OObserver*>::iterator iter = std::find(observers_.begin(), observers_.end(), obs);
			if (iter != observers_.end())
				observers_.erase(iter);
		}
		void notify()
		{
			for (std::list<OObserver*>::iterator iter = observers_.begin(); iter != observers_.end(); ++iter)
				(**iter).update();
		}
};

//----------------------------------------------------------------------------
//	Define the OObserver::OObserver contructor calling attach() method on Sub.
//----------------------------------------------------------------------------

OObserver::OObserver(OSubject* subject) : subject_(subject)
{ 
	subject->attach(this); 
}

//==================================================================================
//                        < Sample Pattern Usage In Classes >         
//==================================================================================

//Sample subject class
class Subject_Class : public OSubject
{
	private:
		std::string name_;
		int num_;
	public:
		Subject_Class(std::string name, int num) : name_(name), num_(num) {}
		void Show_Details() { std::cout<<"Subject Details: " << name_ << " | " << num_ << std::endl<<std::endl; }			
};

//Sample observer class #1
class Obs_Class_I : public OObserver
{
	//Override this for the desired functionality.
	void update() 	{ std::cout<<"Hello World!"<<std::endl; }

	public:
		Obs_Class_I(OSubject* subject) : OObserver(subject) {}
};

//Sample observer class #2
class Obs_Class_II : public OObserver
{
	//Override this for the desired functionality.
	void update() 	{ std::cout<<"Hello Universe!"<<std::endl; }

	public:
		Obs_Class_II(OSubject* subject) : OObserver(subject) {}
};

//==================================================================================
//                    	              < Main >
//==================================================================================

//Main function using the sample classes.
int main()
{
	//Create the subject and output it's details.
	Subject_Class* subject = new Subject_Class("Sample Subject I", 99);
	subject->Show_Details();

	//Create some observers of different types and function calls.
	Obs_Class_I* observer1 = new Obs_Class_I(subject);
	Obs_Class_I* observer2 = new Obs_Class_I(subject);
	Obs_Class_II* observer3 = new Obs_Class_II(subject);
	Obs_Class_II* observer4 = new Obs_Class_II(subject);

	//Call notify() on subject to update all observers.
	std::cout<<"Calling notify which should invoke both observer_class::update functions:"<<std::endl;
	subject->notify();

	//Call unnotify() on subject for two observers.
	std::cout<<std::endl<<"Detached observers 2 and 4."<<std::endl;
	subject->detach(observer2);
	subject->detach(observer4);

	//Call notify() on subject to update all observers.
	std::cout<<std::endl<<"Calling notify which should invoke both observer_class::update functions:"<<std::endl;
	subject->notify();

	//Format output and end the program.
	std::cout<<std::endl<<std::endl;
}

Open in new window

0
 
LVL 12

Expert Comment

by:w00te
ID: 33736161
PS: as normal, you should define these things in multiple files (header in .h, definition in .cpp), but I keep my examples in one file so I can review them easier :)

-w00te
0
 
LVL 5

Assisted Solution

by:greatsubash
greatsubash earned 100 total points
ID: 33741461
0
 

Author Closing Comment

by:sukhoi35
ID: 33759805
Thanks!
0

Featured Post

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction Many of the most common information processing tasks require sorting data sets.  For example, you may want to find the largest or smallest value in a collection.  Or you may want to order the data set in numeric or alphabetical order. …
Introduction This question got me thinking... (http://www.experts-exchange.com/questions/28707487/GLOBALS.html) Why shouldn't we use Globals? This is a simple question without a simple answer.  How do you explain these concepts to a programmer w…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question