Thursday, February 3, 2011

Observer pattern - in an investigative way




Think of a situation when a crime has occurred and the criminal has run away. CID ( Crime Investigation Department ) reached the spot and experiencing the situation , informed the Police Control Room. One of the CID officer using a phone call can easily do this. On response to this request , the  control room informs all the units working on the highways. This informing mechanism is quite simple  and clear.But this can be made complicated by doing the following ... 

One of the officer of CID always remains on phone for doing all the communication works. Then the intension of the officer to be in CID  will be hampered ( He/ She is there for doing investigations , not to remain busy on the phone ).

Observer  pattern is similar to the situation described above. Consider CID as a unit similar to the highway unit that are to be informed.  The Police Control room works as a central communicator . Then all the units are informed on request coming from any of them. ( Sometimes it is not necessary to wait for a request  coming from a unit , Control Room can itself genarate message and notify all.)

In observer pattern there is a Subject( Police Control Room ) who maintains state integrity among all the Observers( units ) In case of any  change in  Stateinformation  ).


Now let's assume that criminal has been traced . A unit informs the control room that they have located the criminal . Then the control room informs

--- CID , to ensure that criminal has been traced.

--- Other units to stop searching ( to prevent any wastage of effort for searching )

In the case above each units ( Observers ) has two states . Let us denote it like the following:

Searching: when all the units are searching on request came from the  Police Control Room.
and 
Free: when a unit has traced the criminal or no notification from the Police Control Room came.

The police control room (Subject) maintains all the units at any of the above state at a given instance of time. 

this is the whole picture of  the observer pattern.  This pattern offers loose coupling .