GoF book says that "Observer pattern should defina a one-to-many dependency between objects so that when one object changes state, all its dependenst are notified and updated automatically". Subscribing to RSS feeds is a nice analogy. You subscribe to RSS feeds to show interest and you become an observer who demand for notification and RSS feeds become the subject and are responsable for providing information to all subscribers. I think this bit of information describing the pattern is enough, now lets see how we implement observer pattern.
Lets assume that we are developing a car controller software. One of the requirements is "Provide visual warning to the driver if seat belts are not locked". To meet the requirement we design
- SeatBelt class which is the subject. This class should notify interested objects about the state changes
- SeatBeltMonitor class is our observer. This class monitors for status change messages provided by the SeatBelt and displays messages
Implementing Observer Pattern in conventional way
Download GoF_Patterns_Observer1.rar (20,36 kb)
It is suggested to specify an interface or abstract classes when dealing with patterns so that the objects we create will adhere to some predefined contract. So we start our implementation by specifying two interfaces ISubject and IObserver
001 public interface ISubject
002 {
003 void RegisterObserver(IObserver observer);
004 void RemoveObserver(IObserver observer);
005 }
006
007 public interface IObserver
008 {
009 void Update(bool locked);
010 }
As I've mentioned above our SeatBelt class is the subject (source) of the state change and should implement the contract so that interested parties shall define their interest to the state changes More...
Currently rated 4.0 by 1 people
- Currently 4/5 Stars.
- 1
- 2
- 3
- 4
- 5