委托与事件(四)

我也来个喝水的订阅发布

事件发行者(Publisher):监控自身信息、数据的变化,当满足某一设定的条件的时候,通知所有的事件订阅者。

事件订阅者(Subscriber):对想要监控的事件进行注册,当接收到订阅者发布的信息、数据后,执行设定的事件处理程序。

先来个效果图:

定义参数类:

 1     public class WaterEventArgs : EventArgs
 2     {
 3         //水的温度
 4         public readonly int temperature;
 5         //构造函数
 6         public WaterEventArgs(int temperature)
 7         {
 8             this.temperature = temperature;
 9         }
10     }

定义烧水类:

 1 public class BoilWater
 2 {
 3     //定义一个烧水的委托(命名:EventHandler结尾)
 4     public delegate void BoilEventHandler(object sender, WaterEventArgs e);
 5     //通过委托定义事件(命名:去除EventHandler之后的部分)
 6     public event BoilEventHandler Boil;
 7 
 8     protected virtual void OnBoil(WaterEventArgs e)
 9     {
10         if (Boil != null)
11         {
12             this.Boil(this, e);
13         }
14     }
15 
16     public void Boiling()
17     {
18         Console.WriteLine("开始烧水。。。");
19         //通过延时模拟烧水的过程
20         Thread.Sleep(8000);
21 
22         for (int temperature = 0; temperature <= 100; temperature++)
23         {
24             //温度大于设定值,开始发布信息
25             if (temperature > 95)
26             {
27                 Thread.Sleep(2000);
28                 OnBoil(new WaterEventArgs(temperature));
29             }
30         }                
31     }
32 }

定义客人类:

 1 public class Client
 2 {
 3     public static void WantWater(object sender,WaterEventArgs e)
 4     {
 5         if (e.temperature < 100)
 6             Console.WriteLine("现在水的温度有{0}度了~", e.temperature);
 7         else
 8             Console.WriteLine("水烧开了,可以喝水啦!!!");
 9     }
10 }

Main函数:

1     //定义烧水类
2     BoilWater boilWater = new BoilWater();
3     //为事件订阅方法
4     boilWater.Boil += new BoilWater.BoilEventHandler(Client.WantWater);
5     //开始烧水
6     boilWater.Boiling();

注:需要先订阅事件,再开始执行程序

原文地址:https://www.cnblogs.com/imstrive/p/6073894.html