c#委托和事件的简单使用,简单介绍observer设计模式

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 委托和事件的简单应用_observer设计模式 { /// <summary> /// 作者:it小金 /// 说明:委托事件的简单应用-使用observer设计模式 /// observer:主要实现一种1对多的依赖关系,当一个对象改变时,依赖于此的对象 /// 会被自动告知 /// </summary> class Program { static void Main(string[] args) { Heater ht = new Heater(); Alarm ar = new Alarm(); Display ds = new Display(); ht.BoilEvent += ar.AlarmBegin; ht.BoilEvent += ds.DisplayShow; ht.BoilFun(); Console.ReadKey(); } } /// <summary> /// 热水器类 /// 包含一个温度字段,和一个烧水方法 /// </summary> class Heater { private int temperature = 0;//默认温度为零 public delegate void BoilHandler(int temper);//定义一个委托 public event BoilHandler BoilEvent;//定义事件,此事件封装了BoilHandler委托 //烧水方法 public void BoilFun() { for (int i = 0; i < 100; i++) { temperature = i; //当温度大于95度的时候,警报器发生声音,液晶屏显示温度 if (temperature >= 95) { BoilEvent(temperature); } } } } /// <summary> /// 警报器类 /// </summary> class Alarm { public void AlarmBegin(int temper) { Console.WriteLine("警报器:嘟嘟~~水温超过95度,当前水温:{0}", temper); } } /// <summary> /// 液晶显示器类 /// </summary> class Display { public void DisplayShow(int temper) { Console.WriteLine("显示器:当前水温:{0}", temper); } } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值