在C#.Net中,观察者模式就是对事件委托的完美应用。
C#代码
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading;
- namespace Observer
- {
- /// <summary>
- /// Observer 观察者模式 入口 .这个才是一个真正的有效的产品。由三个对象构成:烧水品,报警器,显示器
- /// </summary>
- class Program
- {
- static void Main(string[] args)
- {
- Heater heater = new Heater();
- Alarm alarm = new Alarm();
- heater.BoilEvent += alarm.Alert; //注册方法
- heater.BoilEvent += new Alarm().Alert; 给匿名对象注册方法
- heater.BoilEvent += Display.Show; //注册静态方法
- heater.BoilWater(); //烧水,会自动调用注册过对象的方法
- Console.ReadLine();
- }
- }
- #region 热水品成品,由三个部件组成一个有效产品
- //观察的主题,通知所以观察者
- /// <summary>
- /// 热水器
- /// </summary>
- class Heater
- {
- private int temperature; //当前水温
- public delegate void BoilHandler(int t); //委托
- public event BoilHandler BoilEvent; //事件
- public Heater() { }
- /// <summary>
- /// 烧水的过程
- /// </summary>
- public void BoilWater()
- {
- for (int i = 0; i <= 100; i++)
- {
- Thread.Sleep(50); //摸拟烧水耗时,没到设定值时没有动劲
- temperature = i;
- if (temperature > 92)
- {
- Thread.Sleep(1500); //为了显示明显,增加耗时
- if (BoilEvent != null) //如果有对象注册
- {
- BoilEvent(temperature); //调用所有注册对象的方法
- }
- }
- }
- }
- }
- /// <summary>
- /// 报警器
- /// </summary>
- class Alarm
- {
- public Alarm() { }
- public void Alert(int temperature)
- {
- Console.WriteLine("Alarm:嘀嘀嘀,水温已经{0}度了。",temperature);
- }
- }
- /// <summary>
- /// 显示器
- /// </summary>
- class Display
- {
- private Display() { }
- public static void Show(int temperature)
- {
- Console.WriteLine("Display:注意,水温{0}度。", temperature);
- }
- }
- #endregion
- }