Introduction
Understanding the patterns and it's usage had been a cumbersome job when I started first. In addition, I could not get hold of any material where I could get them in the simplest form. So I thought I would just give a try for the guys who are just about to start on it. What I've suggested over here is one of the many possible way that we can implement this pattern. :-)
Details
As the name suggests, it is involved in the monitoring / observing the change of state in any object. To have a brief idea about the mechanism we have 3 components involved and work in tandem with each other.
- The class which is to be observed i.e.
Observerable
- The
Client
class which is interested in knowing the state changes of this Observerable
class
- The class which acts as the mediator between
Client
and Observerable
.
Let's see the structure of this classes for what minimum things that they should have :-
class Observerable
{
public:
bool SetObserver(Observer* apObserver )
{
if ( !apObserver )
return false;
myObserver = apObserver;
return true;
}
void StateChanged( )
{
cout << endl << "State Changed";
myObserver->Notify();
}
private:
Observer* myObserver;
};
This is the class which is to be observed, we have a method SetObserver
to set the mediator / observer class object in it. The Observer
class is the mediator between the Client
class and the Observable
class, so the Observerable
class maintains the object. So in case of any change, the Observer
is notified and in turn the notification is delegated to the clients ( we will see the structure of the Observer
class below).
class Client
{
public:
void Update() { cout << "Update" << endl; }
};
The Client
class will implement the method Update
which is later called by the Observer
class in order to notify the Client
and the Client
updates himself accordingly, so each Client
can have its own implementation for the update and do different things with the same notification. ( pretty much same as document view architecture huh !! )
class Observer
{
public:
bool Attach(Client* );
bool Detach(Client* );
void Notify( );
private:
list<Client*> myClient;
};
This class allows the Client
to attach or detach itself from getting the notification for the Observerable
's changes; also this class maintains the list of clients, which it iterates and calls the update method on each client when notified by the Observerable
class. I have not given the base class for any of the above but we can have a base class which defines some concrete methods. You can have the full source code from the zip I've attached.