观察者模式是设计模式中一种,解决了一对多依赖关系中对象重用问题,多个观察者对象同时监听某一个对象。C#使用委托、事件可以实现观察者模式。
热水器由三个类组成,监听温度:
- 显示器:显示温度
- 告警器:温度过高,发出警告
- 热水器:烧水
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Observer
{
class Program
{
static void Main(string[] args)
{
Heater h1 = new Heater();
Alarm a1 = new Alarm();
h1.AlarmEvent += new Heater.HeaterHandle(a1.MakeAlert);//注册
h1.DisplayEvent += new Heater.HeaterHandle(DisPlay.ShowMsg);//注册静态方法
h1.BoilWater();
Console.ReadLine();
}
}
public class Heater
{
public int temper;//温度
public delegate void HeaterHandle(int temper);//委托声明
public event HeaterHandle AlarmEvent;//事件声明
public event HeaterHandle DisplayEvent;
public void BoilWater()
{
for (int i = 0; i <= 100; i++)
{
temper = i;
if( DisplayEvent != null)
{
DisplayEvent(temper);//通知对象注册的所有方法
}
if (i > 95)
{
if (AlarmEvent != null)
{
AlarmEvent(temper);
}
}
System.Threading.Thread.Sleep(50);
}
}
}
public class Alarm
{
//告警类
public void MakeAlert(int temper)
{
//发出警报
Console.WriteLine("滴滴滴水快烧开了:{0}",temper);
}
}
public class DisPlay
{
//显示器类
public static void ShowMsg(int temper)
{
//静态显示温度方法
Console.WriteLine("正在加热,当前温度:{0}",temper);
}
}
}