Observer Pattern: Defines a one to many relationship between a set of objects. When the state of one object (subject) changes, all others (Observers) are notified.
Use this pattern, if you have objects that have to be updated if data in another object changes. For the observer pattern you will have to use at least two interface classes. One for the subject and one for the observer classes.
interface Observer{
update(); // called by a subject
}
.
interface Subject{
registerObserver(Observer observer);
deregisterObserver(Observer observer);
notifyAll(); // iterates over a list of registered observers calling their
// update method
}
A class which implements the Subject interface has to maintain a list of observers (e.g., List<Observer>). The methods registerObserver and deregisterObserver are used to to add/remove objects implementing the observer interface. Like the Strategy Pattern from my last post, the observer pattern also uses following design principles:- Identify aspects of an application that vary and separate them form what stays the same.
- Program to an interface, not an implementation. Exploit polymorphism by programming to a supertype.
- Favor composition (has-a relationships) over inheritance.
Design Principle 4: Strive for loosely coupled designs between objects that interact. Such objects can interact, but have very little knowledge of each other. This allows for flexible OO systems that can handle change because they minimize the interdependency between objects.
Observer uml (wikipedia) |
Results:
- The only thing that is known to the subject is that the observer implements the observer interface. (Does not need to know the actual class of the observer object)
- The subject can add new observers at any time.
- You will never need to modify the subject to add new types of observers.
- You can reuse subjects or observers independently of each other.
- Changes to either the subject or an observer will not affect the other.
No comments:
Post a Comment