Preface
This article is aimed at more advanced programmers, the example will be in C++ code but since this is a design pattern it is portable to different languages.
You should be fairly familiar with both object orientation and inheritance. Some familiarity with vectors and algorithms is also assumed.A common problem
There are a lot of cases where you want certain objects to keep tabs on what other objects are doing, or what state they are in. As with most common problems other programs have had this problem before, and have made a solution to it. If there’s one thing a programmer needs to be and that’s lazy. Never do yourself what others have probably done better before.
In this example I am going to pretend to be writing a simple game where the player is a sneaky thief trying to grab a jewel. But the jewel is on a pressure plate. If it is removed it will send a signal to the guards’ PDA’s.
Disclaimer: I will keep the implementation of everything very simple, to not confuse you too much.General idea
We will be making two abstract classes, an observer (or listener if you prefer that term) and a subject (or caller). (In java or C# you would be using interfaces for this.)
The observers are just chilling (imagine the guards having a cup of tea or something), until the jewel gets lifted of the panel. At that moment a signal is sent to all the guards that have their PDAs with them. (Have been added to the Subject’s observer list.)

The class that inherits Observer needs to implement the virtual Notify(Observee* observee) method. It will be called by the subject when necessary, in the case of our example when the jewel is removed from its place.

The Subject (‘Observee’ in the code example) does all the hard work. It keeps track of all observers and notifies them when necessary!
The three methods are fairly easy to understand, their name describes what they do. They return a bool so you can check if the execution went as expected.

//this method adds an observer to the vector of observers
bool Observee::AddObserver( Observer* observer )
{
vector<Observer*>::iterator temp = find(m_ObserverVec.begin(), m_ObserverVec.end(), observer);
//Return false if the observer is already in the vector. This is not expected. But there is nothing really wrong either
if ( temp != m_ObserverVec.end() )
return false;
m_ObserverVec.push_back(observer);
return true;
}
//This method removes an observer from the vector
bool Observee::RemoveObserver( Observer* observer )
{
vector<Observer*>::iterator temp = find(m_ObserverVec.begin(), m_ObserverVec.end(), observer);
//Return false if the observer could not be found (and evidently can’t be removed.
if ( temp == m_ObserverVec.end() )
return false;
else
m_ObserverVec.erase(remove(m_ObserverVec.begin(), m_ObserverVec.end(), observer));
return true;
}
//This Method is very important, it triggers all Notify() methods of all observers.
//The specific code in each class that inherits from observer will be executed
bool Observee::NotifyObservers()
{
for_each(m_ObserverVec.begin(), m_ObserverVec.end(), Notifier(this));
//Return false if there are no observers in the vector
return (m_ObserverVec.size() > 0);
}

Implementation
The next thing to do is test out our two classes. We’ll be doing this in a simple win32 console program. This will include a Jewel class (the Subject), a Guard class, and a SecurityDoor class. The last two classes will be our observers.

For details and a sample program you can download the project included at the end.

Summary
So to wrap things up, the Observer/Subject pattern connects classes in a one-to-many relation. It does this trough loose coupling, an important Design Principle.
The class at the ‘one’ end of the relation (the subject) can send a message to all ‘Observers’ that are subscribed to that particular Subject.
It’s also possible to trigger a certain observer with different kinds of Subjects, you just subscribe the observer to different subjects.

Example Project
Seems that I can't attach .rar files, so I'll upload it to a file sharing service. The rar contains a Visual studio 2008 project with all of the above code, and some more.Sample Project Here

This way, you also make sure derived classes are allowed only if they implement all pure virtual functions of base. I guess this form of abstract classes is better in general, as it provides better control over the virtual functions(forcing implementation in derived classes).

ohh i see well i all this time i was thinking some how the constructor calls the overloaded () and didnt pay much attention to for_each ...just taking it as a wrapper for normal for loop

ya what you explained makes sense ...so a notifier object is created with "this" and then () overloaded operator is called with different observer pointer taken iteratively from the vector ... did i get it right ??

ya what you explained makes sense ...so a notifier object is created with "this" and then () overloaded operator is called with different observer pointer taken iteratively from the vector ... did i get it right ??

Yes this seems to be correct. I did explain it a little confusingly in my previous post, so I editted it a bit.

adrainsean, on 01 March 2011 - 05:11 AM, said:

STYN ...i have a another doubt.... why is it that you have disabled copy constructor and assignment operator ??
i didnt get the purpose of it

This is just for safety, I do this with all my classes. If I need them I must first make them public this will remind me to explicitly write them out, so I don't get unexpected behaviour. (As default copy constructors will just copy pointer values and as such don't make a "real" second object, which is obviously the goal of a copy )

Very easy to follow tutorial, thank you very much! One thing though, if a class is abstract I don't think you need to hide the constructors and asssignment operator; you say you've made the constrcutors protected and/or private as to prevent instances of the abstract classes to be created. In C++ I don't think it's possible to instancize abstract classes anyway, so there no need to hide the contructors.

Edit: Nevermind. It's pure abstract classes that you can't instancize (those with functions such as virtual void func() = 0;). I think Overver and Obervee should have been made pure abstract, but that's only a minor complaint.

Thanks for the tutorial. One of the things I enjoy about it is, besides the demonstration of teh patter, there are C++ techniques (for example the use of the overloaded () operator) that make it even mor eintersting.

There is one thing that I don't understand. In Observer.h you have declared a virtual void Notify(...) and this file (Observer.h) is included in Observer.cpp, in Guard.h and the two derived Observers Guard and SecurityDoor. In each of the derived classes (in the .h file), the Notify method is again declared as a virtual.

Since Notify has been declared a virtual function in the first include file in the chain, why is it necessary to make the declaration again in each case? I don't know why the compiler allows it.

Thanks for the tutorial. One of the things I enjoy about it is, besides the demonstration of teh patter, there are C++ techniques (for example the use of the overloaded () operator) that make it even mor eintersting.

There is one thing that I don't understand. In Observer.h you have declared a virtual void Notify(...) and this file (Observer.h) is included in Observer.cpp, in Guard.h and the two derived Observers Guard and SecurityDoor. In each of the derived classes (in the .h file), the Notify method is again declared as a virtual.

Since Notify has been declared a virtual function in the first include file in the chain, why is it necessary to make the declaration again in each case? I don't know why the compiler allows it.

It's been a while since I wrote this, but as I'm still subscribed to this thread so I'll try to answer it.

The compiler allows this because it's not wrong, it is a virtual function. However the virtual keyword in the derived class is not required, since it's information the compiler already knows.

However, I think it's good to have in the derived class because it gives more information about the function without having to dive deeper into the code to other people (or you yourself a few months/years later).

So to summarize: it's not necessary but can make the code a bit clearer. (Of course in a small example like this this is less relevant, but it's still good practice I think.)