Design Pattern-analyze Observer Pattern

Source: Internet
Author: User

 

The observer mode is also called the publish-subscription mode.

 

1. Definition

The observer mode defines a multi-team dependency, allowing multiple observer objects to listen to a single topic object at the same time. When the status of this topic object changes, it notifies all observer objects so that they can update themselves automatically.

 

According to the definition, we can see that the observer mode has two objects and must both exist: the observer and the observer. The observer is the object of the specific operation, and there are multiple objects. If the observer changes, the observer is notified to perform the corresponding operation. It can also be seen that when an object needs to be notified to other objects at the same time, and it does not know how many objects need to be notified, the objects to be notified can be dynamically increased.

In this mode, a target manages all observer objects dependent on it and actively sends notifications when its status changes. This is usually done by calling the methods provided by various observers. This mode is usually used to implement an event processing system.

 

2. Structure Diagram

 

We can see that the observer mode has four types of roles: Abstract observer role, specific observer role, abstract topic role, and specific topic role. Both the topic and the observer use interfaces. The observer uses the topic interface to register with the topic, while the observer uses the observer interface to notify the observer. In this way, the operation between the two is normal and loosely coupled. Therefore, the observer mode is for interface programming, not for implementation programming. Reflects the principle of dependency reversal.

 

3. Example

Let's use an example to illustrate

Wei guanzhi is watching the stock and Yi guanzhi is watching the nbalivestream. In order not to let the boss find out, they asked the front-end boy to inform the boss that he was not there. One day, the boss took the boy to the office to get something. The boy was unable to notify me, and Wei was found by the boss. At this time, the boss can act as a notification, the structure and code are as follows.

Structure chart

 

Code Implementation

 

// Interface subject {void attach (Observer observer); void detach (Observer observer); void y (); string subjectstate {Get; Set ;}} // boss class implementation Interface Class BOSS: Subject {// colleague list private ilist <observer> Observers = new list <observer> (); Private string action; // Add public void attach (Observer observer) {observers. add (observer);} // reduce the public void detach (Observer observer) {observers. remove (observer);} // notify the observer public void Policy () {foreach (Observer o in observers) O. update () ;}// the boss State Public String subjectstate {get {Return Action ;}set {Action = value ;}}}

 

// Abstract observer abstract class observer {protected string name; protected subject sub; public observer (string name, subject sub) {This. name = Name; this. sub = sub;} public abstract void Update ();} // class stockobserver: Observer {public stockobserver (string name, subject sub): Base (name, sub) {}// update your own public override void Update () {console. writeline ("{0} {1} Close the stock market and continue to work! ", Sub. subjectstate, name) ;}// view NBA colleague class nbaobserver: Observer {public nbaobserver (string name, subject sub): Base (name, sub) {}// update your own public override void Update () {console. writeline ("{0} {1} closes the NBA and continues working! ", Sub. subjectstate, name );}}

 

Client

Class program {static void main (string [] ARGs) {// boss Hu hansan boss huhansan = new boss (); // two colleagues: stockobserver tongshi1 = new stockobserver ("Wei Guan Yu", huhansan); nbaobserver tongshi2 = new nbaobserver ("Yi Guan cha", huhansan); // Add a colleague huhansan. attach (tongshi1); huhansan. attach (tongshi2); // reduce colleague huhansan. detach (tongshi1); // The Boss status is huhansan. subjectstate = "I'm Hu hansan back! "; // Notification huhansan. Y ();}}

 

4. Event Delegation

A delegate is a type of reference method. Once a delegate is assigned a method, the delegate has the same behavior as the method. The use of delegate methods can have parameters and return values like any other method. A delegate can be seen as an abstraction of a function and a 'class' of the function. The delegated instance represents a specific function.

Precondition for using delegation: all methods carried by the delegate object must have the same prototype and form, that is, they must have the same parameter list and return value.

 

Example: Use the delegate method in the previous example.

 

Code Implementation

// Interface subject {void notify (); string subjectstate {Get; Set ;}// declare a delegate without parameters and return delegate void eventhandler (); // boss class BOSS: Subject {// declare event update, type: Delegate eventhandler public event eventhandler update; // Private string action of the boss behavior; // update public void every Y () {Update () ;}// the boss status is Public String subjectstate {get {Return Action ;}set {Action = value ;}}}

 

Share colleagues and nbalivestream colleagues remove the parent class and update their respective actions according to their respective changes

// Class stockobserver {private string name; private subject sub; Public stockobserver (string name, subject sub) {This. name = Name; this. sub = sub;} // close the public void closestockmarket () {console. writeline ("{0} {1} Close the stock market and continue to work! ", Sub. subjectstate, name) ;}/// watch nbalivestream class nbaobserver {private string name; private subject sub; Public nbaobserver (string name, subject sub) {This. name = Name; this. sub = sub;} // disable nbalivestream public void closenbadirectseeding () {console. writeline ("{0} {1} closes the NBA and continues working! ", Sub. subjectstate, name );}}

 

Increase and decrease Commission events on the client

Class program {static void main (string [] ARGs) {// boss huhansan = new boss (); // colleague stockobserver tongshi1 = new stockobserver ("Wei Guan Yu ", huhansan); nbaobserver tongshi2 = new nbaobserver ("", huhansan); // added delegation to huhansan. update + = new eventhandler (tongshi1.closestockmarket); huhansan. update + = new eventhandler (tongshi2.closenbadirectseeding); // The Boss status is huhansan. subjectstate = "I'm Hu hansan back! "; // Notification huhansan. Y ();}}


 

5. Differences between the two examples

The difference between the two examples is that, by Delegate, the two sub-classes are separated, the parent class is removed, the method updates are placed in their own classes, and a delegate is declared, the notification event is delegated to the boss. Once the boss's status is updated, the observer's status changes. If one observer is added, a delegate event is added. The observer mode inherits the abstract observer through the specific observer, and the abstract observer relies on the abstract observer.

 

6. Summary

Through the observer mode, the notification dependency between one-to-multiple objects is loose, greatly improving the maintainability and scalability of the program, and well complying with the open-closed principle.

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.