Design Pattern-Observer pattern (observer)

Source: Internet
Author: User

1. First-glance observer Mode

In our life, you must have encountered a situation where the status of a certain thing changes, which will lead to other related changes. Let's talk about martial arts in martial arts. Let's talk about the recent hot TV series "Tianya Mingyue Dao". After reading this episode, the story is probably: the "because of the teacher too" and "guo Jiefang Zhang" fake pass to the Alliance owner password to invite various martial arts doors to the grand villa to open the "snow shovel Conference ", the purpose is to eradicate the martial arts scum "Fu Hongxue" in their eyes ". In fact, this is a typical example of the observer mode.

The observer is: "" and "". (That is, changes in their status will affect changes in other things)

The observer is: Wudang school and other martial arts schools. (That is, changes are made due to changes in the status of the observer)

Gof defines the observer mode: defines a one-to-many dependency between objects. When the State of an object changes, all objects dependent on it are notified and automatically updated.

In fact, the observer mode becomes the publish/subscribe mode again. In this mode, a target object (observer) manages all related objects (observers) that depend on it ), in addition, a notification is triggered when the status of the target object changes. This is usually implemented by using the methods provided by various related objects. The observer mode is usually used as an event processing system.

2. Observer mode implementation

Let's take a familiar example: the user interface can be used as an observer. business data is observed. After the user interface observes changes in business data, it is displayed on the interface.

Now everyone should have a close understanding of the observer mode. How can we implement the observer mode? The observer mode has many implementation methods. Basically, this mode must contain two roles:ObserverAndObserved object. In the preceding example, the business data is the observed object and the user interface is the observer. There is a logical association between the observer and the observer. When the observer changes, the observer will observe the change and respond accordingly. If such an observation process is used between the user interface and business data, the boundary between the interface and data can be ensured, assuming that the ApplicationProgramYou only need to re-build a user interface, and business data does not need to change. In this case, it seems that we need to implement the observer pattern at least:Observer classAndObserver class.

One of the more intuitive ways to implement the observer mode is to use the "Registration-Notification-Revocation registration" form. The key steps are as follows:

Registration: place a container in the object to save the relevant object.

Notification: once the status of the observer object changes, all the observer objects in the container are notified to make corresponding changes.

Unregister: delete an object to be unauthenticated in The Observer object container.

Note:In fact, this implementation method should not only containObserver classAndObserver class. Because when the observer object registers itself to the container of the observer, the observer should not ask the specific type of the observer, but use the observer interface. This advantage is: if there are other observers in the program, as long as the observer is also the same interface implementation. One observer can correspond to multiple observers. When the observer changes, he can send a message to all the observers. It is based on interfaces rather than specific implementations, which provides more flexibility for programs. That is to say, it also contains the base class of the observer class. This facilitates expansion. Let's take a look at the observer pattern class diagram:

Here, subject is the abstract observer, observer is the abstract observer class, attach is to add the observer object to the observer container, and detach is to delete the relevant observer object from the observer container, notify is a specific notification operation, so the observer in the container performs the corresponding operation (update in the Observer ). This design is more in line with the Dependency inversion principle and reduces the coupling of the system. Write nowCodeIt's already quite simple. But there is still a problem.

3. Observer mode vs delegate

We can analyze the above observer mode and find that this implementation has some shortcomings:

(1) the coupling of the system is not completely eliminated.

(2) The operations to be done by all observers may not be the same, that is, they may not all be update operations, and the operations to be done by different observers may not be the same.

The preceding two problems can be rarely solved through delegation. So what?DelegateWhat about it? The delegate is actually similar to the function pointer in C ++. In fact, the delegate is a type of reference method. Once the delegate is assigned a method, the Delegate will have the same behavior as this method. The use of delegate methods can be like any other method, with parameters and return values. A delegate can be considered as a function abstraction and a function class. The delegated instance will represent a specific function, it is also important that the delegate can carry multiple methods, and do not invoke all methods in sequence.

Through the introduction of delegation, do we think we can use delegation to replace the containers in the original observer class? This reduces coupling because the observer does not need to save the observer object. Actually, it is okay. You only need to declare a delegate in the Observer class, and then dynamically assign values to the delegate in the Observer object at the client, the value assigned is the operation to be performed on the observer object when the state of the observer changes. As a result, even if the operations to be performed on the observer object are different, the operation can be well solved. I can only say that delegation is really good ~~~

4. scenarios and benefits of using the observer Mode

The observer mode can be considered in the following cases:

(1) When an abstract model has two aspects, one of which depends on the other, in this case, the observer mode can encapsulate the two objects in independent objects for independent changes and reuse.

(2) When an object changes, it affects other objects and does not know how many objects need to be changed.

(3) When an object must notify other objects, it cannot assume who the other objects are. In other words, you do not want these objects to be tightly coupled.

So what are the benefits of using the observer mode? It mainly reduces the coupling between objects in the system and makes the system easy to expand. In general:

(1) Using object-oriented abstraction, the observer mode allows us to change the object and observer independently, so that the dependency between the two can be loosely coupled.

(2) When the target sends a notification, no observer is required. The notification (which can carry the notification information as a parameter) will be automatically transmitted. The observer determines whether to subscribe to notifications. The target object knows nothing about this.

(3) event in C. The delegate acts as the abstract observer interface, while the object that provides the event acts as the target object. The delegate is more loosely coupled than the abstract observer interface.

Let's take a look at some of the lessons learned.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.