- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Delegate
- {
- //热水器
- public class Heater
- {
- private int temperature;//水温
- public string type = "realfire 007";//型号
- public string area = "China Xian";//产地
- public delegate void BoilEventHandler(Object sender, BoilEventArgs e);//声明委托
- public event BoilEventHandler Boiled;//声明事件
- //定义BoilEventArgs类,传递给Observer所感兴趣的信息
- public class BoilEventArgs : EventArgs
- {
- public readonly int temperature;
- public BoilEventArgs(int temperature)
- {
- this.temperature = temperature;
- }
- }
- //可以供继承自heater的类重写,以便继承类拒绝其他对象对它的监视
- protected virtual void OnBoiled(BoilEventArgs e)
- {
- if (Boiled != null)
- Boiled(this, e);
- }
- //烧水
- public void BoilWate()
- {
- for (int i = 0; i <= 100; i++)
- {
- temperature = i;
- if (temperature > 95)
- {
- BoilEventArgs e = new BoilEventArgs(temperature);
- OnBoiled(e);
- }
- }
- }
- }
- //报警器
- public class Alarm
- {
- //发出嘟嘟嘟的警报声
- public void MakeAlert(Object sender,Heater.BoilEventArgs e)
- {
- Heater heater = (Heater)sender;
- //访问sender中的公共字段
- Console.WriteLine("Alarm :{0}-{1}", heater.area,heater.type);
- Console.WriteLine("Alarm :嘀嘀嘀,水已经{0}度了!", e.temperature);
- }
- }
- //显示器
- public class Display
- {
- //显示水温
- public static void ShowMsg(Object sender,Heater.BoilEventArgs e)
- {
- Heater heater = (Heater)sender;
- //访问sender中的公共字段
- Console.WriteLine("Display:{0}-{1}", heater.area, heater.type);
- Console.WriteLine("Display: 水快开了,当前温度:{0}度。",e.temperature);
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Heater ht = new Heater();
- Alarm alarm = new Alarm();
- ht.Boiled += alarm.MakeAlert;//注册方法
- ht.Boiled += (new Alarm()).MakeAlert;//给匿名对象注册方法
- ht.Boiled += new Heater.BoilEventHandler(alarm.MakeAlert);//也可以这么注册
- ht.Boiled += Display.ShowMsg;//注册静态方法
- ht.BoilWate();
- Console.ReadKey();
- }
- }
- }