Delegate and event in C # (5)-delegate, event and Observer Design Mode

Source: Internet
Author: User

Delegation, events, and Observer Design Patterns

Example

The above example is not enough for the following explanation. Let's take a look at a new example. Because we have already introduced a lot of content, the progress in this section will be slightly faster:

If we have a high-end water heater, we can power it on. When the water temperature exceeds 95 degrees: 1. The speaker will start to send a voice to tell you the temperature of the water; 2. the LCD screen will also change the display of the water temperature to prompt that the water has been burned out.

Now we need to write a program to simulate the water burning process. We will define a class to represent the water Heater. We call it Heater, which has a field representing the water temperature, called temperature; of course, there are also essential methods for water supply heating: BoilWater (), a method for sending voice alarms, MakeAlert (), a method for displaying water temperature, ShowMsg ().

Namespace Delegate {
Class Heater {
Private int temperature; // Water temperature

// Boil water
Public void BoilWater (){
For (int I = 0; I <= 100; I ++ ){
Temperature = I;

If (temperature> 95 ){
MakeAlert (temperature );
ShowMsg (temperature );
}
}
}

// Send a voice alarm
Private void MakeAlert (int param ){
Console. WriteLine ("Alarm: Tick, water has been {0} degrees:", param );
}

// Display the water temperature
Private void ShowMsg (int param ){
Console. WriteLine ("Display: The water is almost open. Current temperature: {0. ", Param );
}
}

Class Program {
Static void Main (){
Heater ht = new Heater ();
Ht. BoilWater ();
}
}
}

Introduction to the Observer Design Mode

The above example can obviously complete the work we described earlier, but it is not good enough. It is assumed that the water heater is composed of three parts: water heater, alarm, and display, which are from different manufacturers and assembled. Then, the water heater is only responsible for boiling water. It cannot issue an alarm or display the water temperature. When boiling water, an alarm is triggered by an alarm, a display prompt, and a water temperature.

At this time, the above example should look like this:

// Water Heater
Public class Heater {
Private int temperature;

// Boil water
Private void BoilWater (){
For (int I = 0; I <= 100; I ++ ){
Temperature = I;
}
}
}

// Alarm
Public class Alarm {
Private void MakeAlert (int param ){
Console. WriteLine ("Alarm: Tick, water has been {0} degrees:", param );
}
}

// Display
Public class Display {
Private void ShowMsg (int param ){
Console. WriteLine ("Display: the water has been burned out. Current temperature: {0. ", Param );
}
}

There is a problem: how to notify the alarm and display when the water is turned on? Before proceeding, let's take a look at the Observer design mode. The Observer design mode mainly includes the following two types of objects:

  • Subject: A monitoring object, which usually contains content of interest to other objects. In this example, the water heater is a monitoring object, and the content that other objects are interested in is the temprature field. When the value of this field is approaching 100, the data is constantly sent to the object that monitors it.
  • Observer: The monitor that monitors Subject. When something in a Subject occurs, it notifies Observer, and the Observer takes corresponding action. In this example, the Observer has an alarm and a monitor, and they take the action of issuing an alarm and displaying the water temperature respectively.

In this example, the sequence of events should be as follows:

  1. The alarm and monitor tell the water heater that it is interested in its temperature (registered ).
  2. The water heater retains reference to alarms and monitors after it is known.
  3. When the water temperature exceeds 95 degrees, the water heater automatically calls the MakeAlert () method of the alarm and the ShowMsg () method of the monitor by referencing the alarm and display.

There are many examples like this. GOF abstracts it and is called the Observer design pattern:The Observer design mode is used to define a one-to-many dependency between objects, so that when the state of an object changes, other objects dependent on it will be automatically notified and updated. The Observer mode is a loosely coupled design mode..

Observer Design Mode for implementing examples

We have already introduced a lot of delegation and events before, and it should be easy to write code now. Now we will give the code directly here and explain it in the annotations.

Using System;
Using System. Collections. Generic;
Using System. Text;

Namespace Delegate {
// Water Heater
Public class Heater {
Private int temperature;
Public delegate void BoilHandler (int param); // declare the delegate
Public event BoilHandler BoilEvent; // declare an event

// Boil water
Public void BoilWater (){
For (int I = 0; I <= 100; I ++ ){
Temperature = I;

If (temperature> 95 ){
If (BoilEvent! = Null) {// if an object is registered
BoilEvent (temperature); // call the methods of all registered objects
}
}
}
}
}

// Alarm
Public class Alarm {
Public void MakeAlert (int param ){
Console. WriteLine ("Alarm: Tick, water has been {0} degrees:", param );
}
}

// Display
Public class Display {
Public static void ShowMsg (int param) {// static method
Console. WriteLine ("Display: The water is almost burned out. Current temperature: {0. ", Param );
}
}

Class Program {
Static void Main (){
Heater heater = new Heater ();
Alarm alarm = new Alarm ();

Heater. BoilEvent + = alarm. MakeAlert; // Registration Method
Heater. BoilEvent + = (new Alarm (). MakeAlert; // Method for registering anonymous objects
Heater. BoilEvent + = Display. ShowMsg; // register the static method

Heater. BoilWater (); // The method of boiling water, which automatically calls the method of registering an object
}
}
}

Output:
Alarm: The water is 96 degrees away:
Alarm: The water is 96 degrees away:
Display: the water is boiling. The current temperature is 96 degrees.
// Omit...

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.