Solved

Observer Design Pattern in C++

Posted on 2010-09-22
5
1,230 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
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
"Disruption" is the most feared word for C-level executives these days. They agonize over their industry being disturbed by another player - most likely by startups.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

707 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now