Click here to Skip to main content
15,894,017 members
Articles / Programming Languages / C++/CLI

Observer Pattern

Rate me:
Please Sign up or sign in to vote.
3.20/5 (10 votes)
9 Oct 20022 min read 73.9K   168   26  
An article that explains Observer patterns in a simple manner
///////////////////////////////////////////////////
// File   : - ObserverPattern.h
// Author : - Nilesh K. Karkhanis
//

#include <list>

using namespace std;

//////////////////////////////////////////////////////
// Client class who is interested in getting notification 
// when the observerable changes
//
class Client
{
public:
	Client() { cout << endl << "C'tor Client"; }
	~Client() { cout << endl << "D'tor Client "; }
	void Update() { cout << "Update" << endl; }
};

//////////////////////////////////////////////////////
// Observer class which monitors the changes of observerable
// and notifies the client of any change
//
class Observer
{
public:
	Observer() { cout << endl << "C'tor Observer ";myClient.erase(myClient.begin(), myClient.end()); }
	~Observer();
	bool Attach(Client* );
	bool Detach(Client* );
	void Notify( );

private:

	list<Client*> myClient;
};

//////////////////////////////////////////////////////
// Class that is to be observered
//
class Observerable
{
public:
	Observerable() { cout << endl << "C'tor Observerable "; myObserver = NULL; }
	~Observerable() {cout << endl << "D'tor Observerable "; }

	bool SetObserver(Observer* apObserver ) 
	{
		if ( !apObserver )
			return false;

		myObserver = apObserver; 

		return true;
	}

	void StateChanged( ) 
	{
		cout << endl << "State Changed";
		myObserver->Notify();
	}

private:
	Observer* myObserver;
};


By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions