Document directory
I. Concepts
The observer mode defines a one-to-many dependency between objects, so that every time an object changes state, all objects dependent on it will be notified and automatically updated (The Observer PatternDefines a one-to-define dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically .).
Ii. Composition of observer Mode
Subject(Object interface observed)
- Specifies the unified interface of concretesubject;
- Each subject can have multiple observers;
Concretesubject(Specific object to be observed)
- Maintains a list of references to all specific observers;
- When the status changes, a notification is sent to all registered observers.
Observer(Observer Interface)
- Specifies the unified interface of concreteobserver;
- Defines an update () method, which is called when the state of the object to be observed changes.
Concreteobserver(Specific observer)
- Maintain a reference to concretesubject;
- Synchronization between the specified status and concretesubject;
- Implement the observer interface to receive concretesubject notifications through the update () method.
Iii. application scenarios
- To update the status of an object, you must synchronously update other objects, and the number of other objects can be dynamically changed.
- The object only needs to notify other objects of its own updates without knowing the details of other objects.
Iv. Advantages and DisadvantagesAdvantages:
- Subject and observer are loosely coupled and can be changed independently.
- When a subject sends a broadcast notification, it does not need to specify the specific observer. The observer can decide whether to subscribe to the subject notification.
- Comply with most grasp principles and common design principles, high cohesion and low coupling.
Defects:
- Due to loose coupling, the code relationship is not obvious and may be difficult to understand.
- If a subject is subscribed to by a large number of observers, it may be efficient during broadcast notifications. (After all, it is just a simple traversal)
References: http://www.cnblogs.com/justinw/archive/2007/05/02/734522.html