This series mainly records what the design pattern intends to be, what issues it wants to solve, and when it can be used; how it solves it, master its structure diagram, remember its key code; be able to think of at least two of its application instances, one in life and one in software; What are the advantages and disadvantages of this model, and what use scenarios are there, what should I pay attention to when using it.
Respect the author. For reposted, please indicate the Blog of Xiaoyang.Http://blog.csdn.net/hacke2
15. Observer Mode
Intention: Defines a one-to-many dependency between objects. When the status of an object changes, all objects dependent on it are notified and automatically updated.
Main Solution: The status of an object changes to the notification of other objects, and the ease of use and low coupling must be considered to ensure high collaboration.
When to use: When the status of an object (target object) changes, all dependent objects (Observer objects) will be notified and broadcast.
Solution: Using object-oriented technology, you can weaken this dependency.
Structure chart:
Key code: In the abstract class, there is an ArrayList for the observer.
Application Instance: 1. during the auction, the auctioneer observes the highest price, and then notifies other contestants of the bidding price. 2. In the travel news to the west, Wukong requests the Bodhisattva to drop down the red baby, And the Bodhisattva spills a place to attract an old tortoise, the tortoise is the observer. He observes the water sprinkling action of the Bodhisattva.
Advantages: 1. The observer and the observer are abstract coupled. 2. Establish a trigger mechanism.
Disadvantages: 1. If an object to be observed has many direct and indirect observers, it takes a lot of time to notify all the observers. 2. If there is a circular dependency between the observer and the observer, the observer will trigger a circular call between them, which may cause the system to crash. 3. The observer mode does not have a mechanism for the observer to know how the observed target object changes. Instead, the observer only knows that the observed target has changed.
Use Cases: 1. There are multiple sub-classes that share the same logic. 2. important and complex methods can be considered as template methods.
Notes: 1. JAVA already supports the observer mode. 2. Avoid circular references. 3. If an observer error occurs during sequential execution, the system may become stuck. asynchronous mode is generally used.