标签:
#region // 定义BoiledEventArgs类,传递给Observer所感兴趣的信息 public class BoiledEventArgs : EventArgs { public readonly int temperature; public BoiledEventArgs(int temperature) { this.temperature = temperature; } } //热水器 public class Heared { public string type = "RealFire 001"; // 添加型号作为演示 public string area = "China Xian"; // 添加产地作为演示 private int temperature; public delegate void BoidHandler(Object sender, BoiledEventArgs e); //声明委托 public event BoidHandler BoidEvent; //声明事件 // 可以供继承自 Heared的类重写,以便继承类拒绝其他对象对它的监视 protected virtual void OnBoiled(BoiledEventArgs e) { if (BoidEvent != null) { // 如果有对象注册 BoidEvent(this, e); // 调用所有注册对象的方法 } } //烧水 public void BoilWater() { for (int i = 0; i < 100; i++) { temperature = i; if (temperature>95) { //建立BoiledEventArgs 对象。 BoiledEventArgs e = new BoiledEventArgs(temperature); OnBoiled(e); // 调用 OnBolied方法 } } } } // 警报器 public class Alarm { public void MakeAlert(Object sender, BoiledEventArgs e) { Heared heater = (Heared)sender; //这里是不是很熟悉呢? //访问 sender 中的公共字段 Console.WriteLine("Alarm:{0} - {1}: ", heater.area, heater.type); Console.WriteLine("Alarm: 嘀嘀嘀,水已经 {0} 度了:", e.temperature); Console.WriteLine(); } } // 显示器 public class Display { public static void ShowMsg(Object sender,BoiledEventArgs e) { //静态方法 Heared heater = (Heared)sender; Console.WriteLine("Display:{0} - {1}: ", heater.area, heater.type); Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", e.temperature); Console.WriteLine(); } } class Program { static void Main() { Heared heater = new Heared(); Alarm alarm = new Alarm(); heater.BoidEvent += alarm.MakeAlert; //注册方法 heater.BoidEvent += (new Alarm()).MakeAlert; //给匿名对象注册方法 heater.BoidEvent += new Heared.BoidHandler(alarm.MakeAlert); //也可以这么注册 heater.BoidEvent += Display.ShowMsg; //注册静态方法 heater.BoilWater(); //烧水,会自动调用注册过对象的方法 } } #endregion
输出为:
Alarm:China Xian - RealFire 001:
Alarm: 嘀嘀嘀,水已经 96 度了:
Alarm:China Xian - RealFire 001:
Alarm: 嘀嘀嘀,水已经 96 度了:
Alarm:China Xian - RealFire 001:
Alarm: 嘀嘀嘀,水已经 96 度了:
Display:China Xian - RealFire 001:
Display:水快烧开了,当前温度:96度。
// 省略 ...
Observer设计模式中主要包括如下两类对象:
在本例中,事情发生的顺序应该是这样的:
类似这样的例子是很多的,GOF对它进行了抽象,称为Observer设计模式:Observer设计模式是为了定义对象间的一种一对多的依赖关系,以便于当一个对象的状态改变时,其他依赖于它的对象会被自动告知并更新。Observer模式是一种松耦合的设计模式
.Net Framework的编码规范:
再做一下说明:
标签:
原文地址:http://www.cnblogs.com/mancomeon/p/4688685.html