The Observer is also a behavioural pattern
The book definition reads:
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
This are the components needed to apply this pattern, usually two interfaces and concrete instances for each of them (another sample is the java implementation, look at the foot note).
Components:
Subject
- Knows its observers
- Has any number of observer
- Provides an interface to attach and detaching observer object at run time
Observer
- Provides an update interface to receive signal from subject
ConcreteSubject
- Stores state of interest to ConcreteObserver objects.
- Send notification to it's observer
ConcreteObserver
- Maintains reference to a ConcreteSubject object
- Maintains observer state consistent with subjects.
- Implements update operation
When to use it:
- When one object changes its state,then all other dependents object must automatically change their state to maintain consistency
- When subject doesn't know about number of observers it has.
- When an object should be able to notify other objects without knowing who objects are.
So, how this really works?
Well in essence you have a subject (the object been listened or followed) that implements a subject interface. In this interface you need to provide a way for other objects to listen to your actions or subscribe, also you must provide another method for objects to stop listening to your non-sense actions and finally provide a method to notify all the objects listening to you, what are you doing.
You also need an observer interface, which must be implemented by the objects listening to your updates. With the update method they will be notified when your subject publishes new data.
Some examples where you may find this pattern:
- RSS feeds
Note:
Java has it's own implementation.
- java.util.Observable (which is a concrete class you have to extend)
- java.util.Observer (which is an interface that you have to implement)
No comments:
Post a Comment