Step by step. NET Design Mode Study note 12, Observer (Observer Mode)

Source: Internet
Author: User

Overview

In the process of building software, we need to establish a "Notification dependency" for some objects-the state of an object (target object) changes, and all dependent objects (Observer objects) will be notified. If such dependency is too tight, the software cannot well resist changes. Using object-oriented technology, you can weaken this dependency and form a stable dependency. To achieve loose coupling of the software architecture.

A software system often requires that some other objects change accordingly when the state of an object changes. There are many design solutions to achieve this, but in order to make the system easy to reuse, we should choose a low coupling design. Reducing the coupling between objects is conducive to the reuse of the system, but at the same time, the designer needs to make the objects with low coupling degrees consistent with the action to ensure a high degree of Collaboration ). The observer pattern is the most important in various design schemes that meet this requirement.

Intention

Defines a one-to-many dependency between objects. When the status of an object changes, all objects dependent on it are notified and automatically updated. [GOF design patterns]

<Design Pattern> structure chart

Figure 1 Structure of the Observer Mode

Role description:

Subject (object interface observed)

Specifies the unified interface of ConcreteSubject;

Each Subject can have multiple observers;

 

ConcreteSubject (object to be observed)

Maintains a list of references to all specific observers;

When the status changes, a notification is sent to all registered observers.

 

Observer (Observer Interface)

Specifies the unified interface of ConcreteObserver;

Defines an update () method, which is called when the state of the object to be observed changes.

 

ConcreteObserver (Specific observer)

Maintain a reference to ConcreteSubject;

Synchronization between the specified status and ConcreteSubject;

Implement the Observer interface to receive ConcreteSubject notifications through the update () method.

Examples in life

The observer defines the one-to-many relationship between objects. When the State of an object changes, all objects dependent on it are notified and automatically updated. The auction demonstrates this mode. Each bidder has a digital sign for bidding. When the auctioneer started the auction, he observed whether there was a sign raising his bid. Each acceptance of a new bid changes the current price of the auction and broadcasts new bids to all bidders.


Figure 2 use the observer mode of the auction example

 

Example:

The traffic lights at the crossroads, pedestrians and drivers are watching the changes of the traffic lights to act. The driver sees the light turns left and the pedestrians see the green light crossing the road. This is exactly in our observer mode, drive and Pedestrian are specific observers, while PilotLamp is the observer interface and TrafficLight. First, let's look at the example diagram:

Code Design:

Create PilotLamp. cs First:

    public interface PilotLamp    {        /// <summary>        /// green light        /// </summary>        void TurnOn();        /// <summary>        /// notice        /// </summary>        string Notice        {            get;            set;         }    }

 

Create DelegateEvent. cs again:

 public delegate void  EventHandler();

 

Create TrafficLight. cs again:

Public class TrafficLight: PilotLamp {public event EventHandler Notices; private string notice; # region GreenLight member public void TurnOn () {if (Notices! = Null) Notices ();} public string Notice {get {return notice;} set {notice = value ;}# endregion}

Create Driver. cs again:

Public class Driver {private string Name; private PilotLamp greenLight; public Driver (string name, PilotLamp greenLight) {this. name = name; this. greenLight = greenLight;} public void GoLeft () {Console. writeLine (string. format ("{1} driver, {0}, please drive to the left. ",
 greenLight.Notice, Name));        }    }

 

Create Pedestrian. cs again:

Public class Pedestrian {private string Name; private PilotLamp greenLight; public Pedestrian (string name, PilotLamp greenLight) {this. name = name; this. greenLight = greenLight;} public void GoThrough () {Console. writeLine (string. format ("{0} comrade, {1}, please move forward. ",
 Name, greenLight.Notice));        }    }

 

Finally, call:

Public partial class Run: Form {public Run () {InitializeComponent ();} private void btnRun_Click (object sender, EventArgs e) {TrafficLight trafficLight = new TrafficLight (); driver driverOne = new Driver ("zhangsan", trafficLight); Driver driverTwo = new Driver ("Li Si", trafficLight); Pedestrian pedestrianOne = new Pedestrian ("Wang Wu", trafficLight ); pedestrian pedestrianTwo = new Pedestrian ("Ma ", trafficLight); trafficLight. notices + = new Observer. eventHandler (driverOne. goLeft); trafficLight. notices + = new Observer. eventHandler (driverTwo. goLeft); trafficLight. notices + = new Observer. eventHandler (pedestrianOne. goThrough); trafficLight. notices + = new Observer. eventHandler (pedestrianTwo. goThrough); trafficLight. notice = "the green light is on. "; trafficLight. turnOn ();}}

Select console application for output:

The result is as follows:

Related Article

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.