Never give up

C# 中Delegate and Event 用法,其中采用了Observer Design Module思想

上一篇 / 下一篇  2016-12-06 12:24:05

这里就出现了一个问题:如何在水烧开的时候通知报警器和显示器?在继续进行之前,我们先了解一下Observer设计模式,Observer设计模式中主要包括如下两类对象:

  1. Subject:监视对象,它往往包含着其他对象所感兴趣的内容。在本范例中,热水器就是一个监视对象,它包含的其他对象所感兴趣的内容,就是temprature字段,当这个字段的值快到100时,会不断把数据发给监视它的对象。
  2. Observer:监视者,它监视Subject,当Subject中的某件事发生的时候,会告知Observer,而Observer则会采取相应的行动。在本范例中,Observer有警报器和显示器,它们采取的行动分别是发出警报和显示水温。

在本例中,事情发生的顺序应该是这样的:

  1. 警报器和显示器告诉热水器,它对它的温度比较感兴趣(注册)。
  2. 热水器知道后保留对警报器和显示器的引用。
  3. 热水器进行烧水这一动作,当水温超过95度时,通过对警报器和显示器的引用,自动调用警报器的MakeAlert()方法、显示器的ShowMsg()方法。

类似这样的例子是很多的,GOF对它进行了抽象,称为Observer设计模式:Observer设计模式是为了定义对象间的一种一对多的依赖关系,以便于当一个对象的状态改变时,其他依赖于它的对象会被自动告知并更新。Observer模式是一种松耦合的设计模式。

实现范例的Observer设计模式

我们之前已经对委托和事件介绍很多了,现在写代码应该很容易了,现在在这里直接给出代码,并在注释中加以说明。




using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate
{
    // Heater
    public class Heater
    {
        private int temperature;
        public delegate void BoilHandler(int param);   //Delegater Declaration
        public event BoilHandler BoilEvent;        //Event Declaration

        // Boil water
        public void BoilWater()
        {
            for (int i = 0; i <= 100; i++)
            {
                temperature = i;

                if (temperature > 95)
                {
                    if (BoilEvent != null)
                    { //If no object is registed
                        BoilEvent(temperature);  //Invoke method of all Instance
                    }
                }
            }
        }
    }

    // Alarm
    public class Alarm
    {
        public void MakeAlert(int param)
        {
            Console.WriteLine("Alarm:Dididi,Water Temperature is : {0}", param);
            Console.WriteLine("");
        }
    }

    // Monitor
    public class Display
    {
        public static void ShowMsg(int param)
        { //Static Method
            Console.WriteLine("Display:Nearly boiled,water temperature is:{0}", param);
            Console.WriteLine("");
        }
    }

    class Program
    {
        static void Main()
        {
            Heater heater = new Heater();
            Alarm alarm = new Alarm();

            heater.BoilEvent += alarm.MakeAlert;    //Method Registration
            heater.BoilEvent += (new Alarm()).MakeAlert;   //Method Registration
            heater.BoilEvent += Display.ShowMsg;       //Static Method Registration

            heater.BoilWater();   //Boiling Water,Invoke the Method whose Instance is registed automatically
            Console.ReadKey();
        }
    }
}

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-04-27  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 21527
  • 日志数: 14
  • 建立时间: 2016-10-17
  • 更新时间: 2017-06-28

RSS订阅

Open Toolbar