且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#事件和观察者设计模式

更新时间:2022-05-30 10:10:09

 

Observer设计模式简介
现在假设热水器由三部分组成:热水器、警报器、显示器,它们来自于不同厂商并进行了组装。那么,应该是热水器仅仅负责烧水,它不能发出警报也不能显示水温;在水烧开时由警报器发出警报、显示器显示提示和水温。

 

Observer 设计模式中主要包括如下两类对象

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

 

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

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

 ()方法、显示器的 ShowMsg()方法

 

    /// <summary>
    /// 热水器
    /// </summary>
    class Heater
    {
        public int temperature;                                   // 监视对象
        public delegate void BoilWaterHandler(int temperature);   // 声明委托
        public event BoilWaterHandler BoilWaterEvent;             // 注册事件
   
        public void BoilWater()
        {
            for (int i = 0; i <= 100; i++)
            {
                temperature = i;
                if (temperature > 95)
                {
                    if (BoilWaterEvent != null)
                    {
                        BoilWaterEvent(temperature);
                    }
                }
            }
        }
    }

    /// <summary>
    /// 警报器
    /// </summary>
    public class Alarm
    {
        public void MakeAlert(int temp)
        {
            Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:", temp);
        }
    }

 

    /// <summary>
    /// 显示器
    /// </summary>
    public class Show
    {
        public void ShowMsg(int temp)
        {
            Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", temp);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Heater Myheater = new Heater();
            Alarm MyAlarm = new Alarm();
            Show Myshow = new Show();

            Myheater.BoilWaterEvent += MyAlarm.MakeAlert;
            Myheater.BoilWaterEvent += Myshow.ShowMsg;       

           // Myheater.BoilWaterEvent+=(new Show()).ShowMsg;
            Myheater.BoilWater();                             // 烧水,会自动调用注册过对象的方法

            Console.ReadLine();
        }
    }

 

转自:

张子阳
www.tracefact.net