Observer 设计模式 了解委托与事件的使用
2017-12-18 16:33
555 查看
namespace Delegate { public class Heater { private int temperature; public delegate void BoilHandler(int param); public event BoilHandler BoilEvent; public void BoilWater() { for (int i = 0; i <= 100; i++) { temperature = i; if (temperature > 95) { if (BoilEvent != null) { BoilEvent(temperature); // 调用所有注册对象的方法 } } } } } public class Alarm { public void MakeAlert(int param) { Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:", param); } } public class Display { public static void ShowMsg(int param) // 静态方法 { Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", param); } } class Program { static void Main() { Heater heater = new Heater(); Alarm alarm = new Alarm(); heater.BoilEvent += alarm.MakeAlert; // 注册方法 heater.BoilEvent += (new Alarm()).MakeAlert; // 给匿名对象注册方法 heater.BoilEvent += Display.ShowMsg; // 注册静态方法 heater.BoilWater(); // 烧水,会自动调用注册过对象的方法 } } }
输出为:
// ************************************************************************
Alarm:嘀嘀嘀,水已经 96 度了:
Alarm:嘀嘀嘀,水已经 96 度了:
Display:水快烧开了,当前温度:96 度。
// 省略...
// ************************************************************************
相关文章推荐
- C#设计模式之十九:Observer模式(使用委托、事件)
- Observer 设计模式(委托和事件的使用)
- 委托、事件与Observer设计模式
- C#中使用委托和事件实现观察者模式(observer pattern)
- C#中的委托和事件(5)---委托、事件与Observer设计模式
- 委托、事件与Observer设计模式
- C#中使用委托和事件实现观察者模式(observer pattern)
- Observer设计模式——委托事件
- [学习笔记]c#中的委托、事件、Func、Predicate、Observer设计模式以及其他
- 委托、事件与Observer设计模式
- c#委托和事件的简单使用,简单介绍observer设计模式
- 委托、事件与Observer设计模式
- C#中的委托和事件--5.委托、事件与Observer设计模式
- C#,由委托到Observer设计模式,再到事件机制
- 使用委托和事件实现观察者模式(Observer Pattern)
- .Net中使用事件和委托实现Observer模式(二)
- C# 中的委托和事件与Observer设计模式
- 委托、事件与Observer设计模式
- 委托、事件与 Observer 设计模式
- 委托、事件与Observer设计模式