In-depth understanding of the Observer pattern

First, look at the observer pattern design class diagram:

definition:

The observer pattern is a software design pattern one. In this mode, a target object dependencies to manage all of its observer objects, and proactive notification when the state itself changes. This is usually achieved through a method call provided for each viewer. This model is often used in real-time event processing system.

Features:

Establishing a dependency relationship between the object and the object will automatically notify other objects when an object changes, the corresponding other objects react. Here, the object is changed is referred to as an observation target, and the object is referred to as a viewer is notified, the observation target may correspond to a plurality of observers, there is no connection between them and the viewer, can be increased as needed and delete viewer to make the system easy to extend. Establishing an abstract model viewer coupled between the observation target and the observer. Observer mode supports broadcast communications, observer mode meet the requirements of "opening and closing principle".

structure:

The observer pattern contains several roles as follows:

  • Subject: goal
  • ConcreteSubject: Target
  • Observer: observer
  • ConcreteObserver: specific observer

Disadvantages:

  • If an observation target object has many direct and indirect observer, it will notify all observers have to spend a lot of time.
  • If there is a circular dependency between the observer and the observed target, observe the target will trigger calls to circulate between them, may cause the system to crash.
  • The observer pattern is no mechanism to let the viewer know that the target object observed is how change happens, but just know to observe the target has changed.

Applicable scene:

  • To change an object, it will result in a corresponding one or more objects to be changed corresponding to occur, particularly not know how many objects to be changed, the degree of coupling between objects can be reduced.
  • An object to notify other objects without knowing which specific object.
  • You need to create a trigger in the system chain, will affect the behavior of the object A B, B object will affect the behavior of C, you can create a trigger chain using the Observer pattern.

Guess you like

Origin www.cnblogs.com/zhuziqiya/p/12156365.html