Observer (Viewer) mode

Source: Internet
Author: User

1. Overview

Some object-oriented programming methods provide the ability to construct complex network interconnection between objects. When objects are connected together, they can provide services and information to each other.

In general, when the state of an object changes, you still need to be able to communicate with each other between objects. But for a variety of reasons, you may not want to make changes to your code because of changes in the code environment. Perhaps, you just want to improve the communication code based on your specific application environment. Or, you just want to simply reconstruct the communication code to avoid the interdependence and dependency between classes and classes.

2. Questions

How do you notify other objects when the state of an object changes? Is there a need for a dynamic scenario-a scenario that allows free connections, just as you would allow a script to execute?

3. Solution

Observation Mode: Defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and automatically updated.

The observation mode allows an object to focus on the state of other objects, and the observational pattern provides an observation structure, or a subject and an object, for the observed person. The subject, which is the observer, can be used to contact all observers who observe it. The object, or observer, that is used to accept the change of the subject state is the collaboration of an observable class (that is, the subject) with one or more of the classes (i.e., objects) that observe it. All registered observers will be notified whenever the state of the object being observed changes.
The observed pattern is separated from the Observer (object) by the Observer (subject). Thus, each observer can take its own action according to the change of the subject. (observational mode, like Publish/subscribe mode, is also a model that effectively describes the interaction between objects.) The observation mode is flexible and powerful. For the Observer, the additional resource overhead of querying which classes require their own state information and each use of those state information is no longer present. In addition, an observer can register and unregister at any appropriate time. You can also define a number of specific observation classes to perform different operations in a real-world application.
Splitting a system into a series of mutually collaborative classes has a common side effect: the need to maintain consistency between related objects. We do not want to keep the various types tightly coupled in order to maintain consistency, because it reduces their reusability.

4. Applicability

You can use observer mode in any of the following situations:
• When an abstract model has two facets, one aspect depends on the other. The two are encapsulated in separate objects so that they can be individually changed and reused.
• When a change to an object needs to change other objects at the same time, it is not known how many objects need to be changed.
• When an object must notify other objects, it cannot assume that other objects are who. In other words, you don't want these objects to be tightly coupled.

5. Structure

6. Composition of the pattern

The Observer pattern contains the following roles:
Goal (Subject): The target knows its observer. There can be any number of observers observing the same target. Provides an interface for registering and deleting observer objects.
Target (ConcreteSubject): The status is deposited into each Concreteobserver object.
Observer (Observer): Defines an update interface for objects that need to be notified when a target is changed. Notifies its individual observers when its state has changed.
Specific observer (CONCRETEOBSERVER): maintains a reference to the ConcreteSubject object. Stores the state, which should be consistent with the state of the target. Implements an update interface for O B S e R v E R to align its state with the state of the target.

7. Effects

Observer mode allows you to change the target and observer independently. You can reuse the target object individually without having to reuse its observers at the same time, and vice versa. It also allows you to increase the observer without altering the target and other observers.
The following are some other advantages of the Observer pattern:
1) The Observer pattern can realize the separation of the presentation layer and the data logic layer, and defines a stable message update delivery mechanism, which abstracts the update interface, so that there can be a variety of different presentation layers as the specific observer role.
2) Create an abstract coupling between the observation target and the Observer: only one object knows that it has a series of observers, each of which conforms to the simple interface of the abstract observer class. The target does not know which specific class any observer belongs to. This coupling between the target and the observer is abstract and minimal. Because the target and the observer are not tightly coupled, they can belong to different levels of abstraction in a system. A target object at a lower level can communicate with a higher-ranking observer and notify it, thus preserving the integrity of the system hierarchy. If the target is mixed with the observer, the resulting object will either traverse two levels (in violation of the hierarchy) or must be placed in one layer of the two layers (which may damage the hierarchy abstraction).
3) Support Broadcast communication: Unlike the usual request, the notification sent by the target does not need to specify its recipient. Notifications are automatically broadcast to all relevant objects that have been registered with the target object. The target object does not care how many objects are interested in itself; its sole responsibility is to inform its observers. This gives you the freedom to add and remove observers at any time. Processing or ignoring a notification depends on the observer.
4) The Observer pattern conforms to the "open and close principle" requirement.
the disadvantage of the observer pattern
1) If a viewing target has many direct and indirect observers, it will take a lot of time for all observers to be notified.
2) If there is a cyclic dependency between the observer and the observation target, observing the target triggers a cyclic call between them, which can cause the system to crash.
3) The Observer pattern does not have a mechanism for the observer to know how the target object is changing, but only to know that the observation target has changed.
4) Unexpected updates because an observer does not know the existence of other observers, it may be ignorant of the ultimate cost of changing the target. A seemingly harmless operation on the target may result in a series of updates to the observer and those objects that depend on those observers. In addition, if the dependency criterion is defined or poorly maintained, it often causes incorrect updates, which are often difficult to capture.
The simple update protocol does not provide specific details about what has changed in the target, which makes the above problem more serious. If no other protocol helps observers find out what has changed, they may be forced to try to reduce the change.

8. Implement

#include <iostream>#include<list>using namespacestd;classobserver{ Public:     Virtual voidUpdate (int) =0;};classsubject{ Public:     Virtual voidAttach (Observer *) =0; Virtual voidDetach (Observer *) =0; Virtual voidNotify () =0;};classConcreteobserver: Publicobserver{ Public: Concreteobserver (Subject*psubject): M_psubject (psubject) {}voidUpdate (intvalue) {cout<<"Concreteobserver get the update. New State:"<<value<<Endl; }Private: Subject*M_psubject;};classConcreteObserver2: Publicobserver{ Public: ConcreteObserver2 (Subject*psubject): M_psubject (psubject) {}voidUpdate (intvalue) {cout<<"ConcreteObserver2 get the update. New State:"<<value<<Endl; }Private: Subject*M_psubject;};classConcreteSubject: Publicsubject{ Public:     voidAttach (Observer *pobserver); voidDetach (Observer *pobserver); voidNotify (); voidSetState (intState ) {M_istate=State ; }Private: Std::list<observer *>m_observerlist; intm_istate;};voidConcretesubject::attach (Observer *pobserver) {M_observerlist.push_back (pobserver);}voidConcreteSubject::D Etach (Observer *pobserver) {M_observerlist.remove (pobserver);}voidconcretesubject::notify () {std::list<observer *>::iterator it =M_observerlist.begin ();  while(It! =M_observerlist.end ()) {          (*it)Update (m_istate); ++it; }}intMain () {//Create SubjectConcreteSubject *psubject =NewConcreteSubject (); //Create ObserverObserver *pobserver =NewConcreteobserver (Psubject); Observer*pobserver2 =NewConcreteObserver2 (Psubject); // Change of the statePsubject->setstate (2); //Register The ObserverPsubject->Attach (Pobserver); Psubject-Attach (POBSERVER2); Psubject-Notify (); //Unregister The ObserverPsubject->Detach (Pobserver); Psubject->setstate (3); Psubject-Notify (); DeletePobserver; DeletePObserver2; DeletePsubject;}

9. With other related modes

1) Terminator mode mediator: by encapsulating Complex update semantics, Changemanager acts as a mediator between the target and the observer.
2) Single mode Singleton:changemanager can use singleton mode to ensure that it is unique and can be accessed globally
Of

10. Summary and Analysis

Through the observer mode, the notification dependency between a pair of objects becomes looser, which greatly improves the maintainability and extensibility of the program, and conforms to the open-close principle.

Observer (Viewer) mode

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.