Story of design pattern---observer pattern

Source: Internet
Author: User

Intention:

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.

Applicability:

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.


simulate a game of tearing up a famous brand in the "run brother"
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Security.Cryptography;usingSystem.Text;usingSystem.Threading.Tasks;namespacedesignermodel.observer{ Public Abstract classIObserver { Public Abstract voidUpdate (stringmsg); }    /// <summary>    ///Big Broadcast/// </summary>     Public classSubject {PrivateList<observer> observers =NewList<observer>();  Public voidAttach (Observer o) {observers.        ADD (o); }         Public voidDetach (Observer o) {observers.        Remove (o); }         Public voidNotifyobservers (stringmsg) {            foreach(varIteminchobservers) {Item.            Update (msg); }        }    }    /// <summary>    ///Game Players/// </summary>     Public classObserver:iobserver { PublicObserver (stringname) {Name=name; }         Public stringName {Get;Set; }  Public Override voidUpdate (stringmsg) {Console.WriteLine ( This. Name +"information received:"+msg); }         Public stringCreatenum () {RNGCryptoServiceProvider CSP=NewRNGCryptoServiceProvider (); byte[] BYTECSP =New byte[Ten]; Csp.            GetBytes (BYTECSP); returnbitconverter.tostring (BYTECSP); }    }     Public classGamerule {PrivateSubject Subject {Get;Set; }  Publicgamerule (Subject Subject) {Subject=subject; }        /// <summary>        ///Tear Brand/// </summary>        /// <param name= "Ob1" ></param>        /// <param name= "Ob2" ></param>        /// <returns></returns>         PublicObserver ripthenameplate (Observer ob1, Observer ob2) {Random rand1=NewRandom (1); Random Rand2=NewRandom (5); intNUM1 = Rand1. Next (1, +); intnum2 = Rand2. Next (1, +); if(num1>num2) {subject.notifyobservers (OB1). Name+" out"); returnOb1; }            Else{subject.notifyobservers (OB2). Name+" out"); returnOb2; }        }    }     Public Static classClient { Public Static voidRun () {Subject sub=NewSubject (); Observer Observer1=NewObserver ("Deng Chao"); Observer Observer2=NewObserver ("Zheng Kai"); Observer Observer3=NewObserver ("Baby"); Observer Observer4=NewObserver ("Baubert"); Observer Observer5=NewObserver ("Chenhe"); Observer Observer6=NewObserver ("Li Chen"); Sub.            Attach (Observer1); Sub.            Attach (OBSERVER2); Sub.            Attach (OBSERVER3); Sub.            Attach (OBSERVER4); Sub.            Attach (OBSERVER5); Sub.            Attach (OBSERVER6); //let Deng Chao and Zheng Kai tear the brand            NewGamerule (sub).                       Ripthenameplate (Observer1, Observer2);        Console.read (); }    }}

The relationship between the target and the viewer

According to the pattern definition, there is a typical 1-to-many relationship between the target and the observer, but note that if the Observer has only one, it can also be a relationship of 1 to 1, which also allows the observer pattern to be considered when dealing with the state of an object that affects another object.

Similarly, an observer can observe multiple targets, which is problematic if the notification Update method defined by the observer for multiple targets is the Update method, because it is necessary to accept notifications for multiple targets, and if it is an update method, it needs to be differentiated within the method. In the end, the notification of this update comes from which goal, different targets have different follow-up actions.

In general, the observer should be different from the observer target to define different callback methods, so that the implementation is the simplest and does not need to be differentiated within the Update method.

One-way dependency, in the observer pattern, the observer and the target are one-way dependent, and only the observer relies on the target, and the target is not dependent on the observer.

The initiative between them is in the hands of the target, and only the target knows when to notify the Observer, and the observer is always passive throughout the process. Passive waiting for a target notification. Wait for the target to pass the value to it.

To the goal, all observers are the same, and the goals are treated equally. It is also possible to achieve a differentiated approach to the observer by controlling it in the target. For example, some states have changed, and only some observers need to be notified. But that's a slightly distorted usage. Not a standard, primitive observer pattern.

The basic implementation Description:

1, the target realization object to be able to maintain the observer's registration information, the simplest implementation of the scenario as in the previous example, a collection to save the observer's registration information.

2, the target implementation of the object needs to maintain the state of the notification, in general, the target itself in the case of deformation, it can also be the state of other objects.

3, the specific observer realizes the object needs to be able to accept the target notification, can accept the target transmission data, or is able to take the initiative to obtain the target data, and carries on the subsequent processing

4, if it is an observer target to observe multiple targets, then in the Observer's Update method, it is necessary to determine which target is the notification. A simple solution is to extend the Update method, for example, to pass a parameter in the method to differentiate, etc., and there is an easier way to simply define a different callback method.

Naming recommendations

1, the Observer pattern is also known as the publish-subscribe mode

2, the definition of the target interface, recommended after the name with subject

3, the definition of the Observer interface, it is recommended to follow the name Observer

The Update method of the Observer interface, the proposed name is update, of course, the parameters of the method can be determined according to the circumstances, the number of parameters, type Unlimited.

Time to trigger notification:

In the implementation of the observer mode, it is important to pay attention to the timing of triggering the notification, in general, after the completion of the state maintenance triggered, because the notification will pass data, can not be notified after the change of data, which is prone to problems, will cause the observer and target object state inconsistent.

For example, when a target triggers a notification, there is an observer to take the value, and the target has not yet updated the data, which obviously caused the error.

Two modes of the Observer pattern:

Push mode: The target object actively pushes the target's details to the observer, regardless of whether the observer needs it, the information that is pushed is usually all or part of the data of the target object, equivalent to the broadcast communication

Pull mode: The target object only passes a small amount of information when it notifies the observer. If the viewer needs more specific information. An observer takes the initiative to the target object, which is the equivalent of the observer pulling data from the target object. In the general implementation of this pattern, the target object itself is passed to the observer through the Update method, which can be obtained by this reference when the observer needs to obtain the data.

The push mode is the assumption that the target object knows the data that the observer needs, and the pull mode is that the target object does not know what data the observer needs, and if there is no way, simply pass it on to the observer and let the Observer take the value on demand.

Push mode may make it difficult to reuse the observer object because the Observer-defined Update method is defined on demand and may not be considered in the absence of consideration. This means that a new update method may be required when new situations arise, or simply re-implement the observer. The pull mode does not cause this situation, because the parameter of the Update method in pull mode is the target object itself, which is basically the largest data collection that the target object can pass, and can basically adapt to the needs of various situations.

Story of design pattern---observer pattern

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.