Subject (target): The target is also called the subject, which refers to the object being observed. A set of observers is defined in the target, and an observation target can be observed by any number of observers, which provides a series of methods for adding and deleting the Observer object, and it defines the notification method notify (). The target class can be an interface, or it can be an abstract class or a concrete class.
Concreteobserver (Specific observer): maintains a reference to a specific target object in a specific observer, which stores the state of the specific observer, which needs to be consistent with the state of the specific target It implements the update () method defined in the abstract observer observer. Typically, when implemented, you can invoke the attach () method of a specific target class to add itself to the collection of target classes or to remove itself from the collection of target classes by means of the detach () method.
The Observer pattern creates an abstract coupling between the observed object and the observer. Observing a target requires only maintaining a collection of abstract observers, without having to know its specific observer. Since observation targets and observers are not tightly coupled, they can belong to different levels of abstraction.
The Observer pattern supports broadcast communication, and observing the target sends notifications to all registered observer objects, simplifying the difficulty of a one-to-many system design.
Observer pattern satisfies the requirement of "open and close principle", adding new observer without modifying the original system code, it is convenient to add new observation target when there is no correlation between the specific observer and the observation target.
You can consider using the observer pattern in the following situations:
(1) an abstract model has two facets, one of which relies on another, encapsulating the two aspects in separate objects so that they can be individually changed and reused.
(2) the change of one object causes one or more other objects to change, without knowing exactly how many objects will change or who they are.
(3) a trigger chain needs to be created in the system, the behavior of the A object will affect the B object, and the behavior of the B object will affect the C object ..., you can use the observer pattern to create a chain-triggered mechanism.
Thank you, Miss Liu. About design mode this piece, my blog basically is oneself study Liu Wei teacher design pattern of some summary, many Xiai Liuwei teacher's dedication.
Observer Pattern Learning