Saturday 21 January 2012

Observer Pattern


The observer pattern defines one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.
This pattern is described as one similar to a newspaper subscription. The publisher sends newspapers to the subscribers whenever a paper is released.  Potential subscribers have the ability to subscribe and subscribers have the ability to a unsubscribe.




According to the observer design pattern, the object distributing the data (publisher) is called the subject. Those objects that receive the data (subscriber) are called observers.
I have developed an example of the object pattern using the following example.
The example I used is a model of the rate of growth of different tress within a particular niche.  Trees situated within the same environment receive the same parameters i.e.  The same amount of Sun, Rain and Carbon dioxide. Even though they receive the same parameters the effect these parameters have on each tree is different.  i.e.  They differ in their level of growth, the amount oxygen they produce and the fruits grown.
Nature is designed to provide the sustenance and in this case will be the SUBJECT. The trees retrieve this sustenance and will in this case be the OBSERVER.

Below shows a class diagram of the observer pattern and how it will be implemented in code.
 

 Code

This is the subject interface which will be implemented by the Subject class nature.
This is the observer interface which will be implemented by the tree classes
 The subject class

Below is an observer class 




the programs main function
when complied these are the results I received
















Conclusion

I constructed this code as a simple example to get acquainted with the fundamental implementation of the observer pattern.
The benefits of the observer pattern is that if you wish to change the parameters of the subject you don’t have to make changes to all the observers. The subject and observers are loosely coupled so it doesn’t matter what type the observers are, as long as they implement the Observer interface then everything will run nice. The observer could be a colony of ants or a mushroom.  You could also change how each observer manipulates the parameter data without having to edit any other of the registered observers or the subject itself. 
Once I have learned the fundamentals of each design pattern I will revise the objective pattern as its complexity extends beyond the small example I gave. For instance the iObserver and iObservable interface in .Net is something I hope to explore.

 


No comments:

Post a Comment