observer | | 6.6 - The Observer Pattern | - connecting an observer directly to an observable so that they both have references to each other
- making the observers subclasses of the observable
| design pattern | How do you reduce the interconnection between classes, especially between classes that belong to different modules or subsystems? | - When you create a two-way association between two classes, the code for the classes becomes inseparable
- When you compile one, the other one has to be available since the first one explicitly refers to it
- This means if you want to reuse one of the classes, you also have to reuse the other; similarly, if you change one, you probably have to change the other
| A pattern found in class diagrams in which instances of one class are informed of changes to instances of a second class | to separate the model^2 from the controller in the Model-View-Controller architecture | - Create an abstract class «Observable» that maintains a collection of «Observer» instances.
- The «Observable» class is very simple; it merely has a mechanism to add and remove observers, as well as a method notifyObservers that sends an update message to each «Observer».
- Any application classes can declare itself to be a subclass of «Observable».
- «Observer» is an interface, defining only an abstract update method.
- Any class can thus be made to observe an Observable by declaring that it implements the interface, and asking to be a member of the observer list of the «Observable».
- The «Observer» can then expect calls to its update method whenever the «Observable» changes.
- Using this pattern, the «Observable» neither has to know the nature of the classes that will be interested in receiving the update messages, nor what they will do with this information.
| - You want to maximize the flexibility of the system to the greatest extent possible.
| one of the Gang of Four patterns. |