//事件(热水器)
namespace _16ClassCode
{
public delegate void BoilWater(int temperature);
//热水器
class WaterHeater
{
public event BoilWater boilWaterEvent;
private float temperature;
private static WaterHeater wh;
private WaterHeater() { }
public static WaterHeater Instance()
{
if(wh == null)
{
wh = new WaterHeater();
new Display();
new Alarm();
}
return wh;
}
//烧水
public void BoilWater()
{
for (int i = 0; i <= 100; i++)
{
temperature = i;
if(temperature > 90)
{
if(boilWaterEvent != null)
{
boilWaterEvent((int)temperature);
}
}
}
}
}
//警报
class Alarm
{
public Alarm()
{
WaterHeater wh = WaterHeater.Instance();
wh.boilWaterEvent += this.StartWaringSystem;
}
public void StartWaringSystem(int temperature)
{
Console.WriteLine("嘟嘟嘟嘟嘟嘟,当前温度{0}",temperature);
}
}
//显示器
class Display
{
public Display()
{
WaterHeater wh = WaterHeater.Instance();
wh.boilWaterEvent += this.ShowMessage;
}
public void ShowMessage(int temperture)
{
Console.WriteLine("好热,好热~~");
}
}
}
//观察者模式
interface ISubject //抽象发布者
{
void Notify();
string Subject { get; set; }
}
//事件委托处理
delegate void PatrolHandler();
class Teacher : ISubject
{
//事件不可以当做形参传递,但是委托可以
public event PatrolHandler Update;
public string Subject { get; set; }
public void Notify()
{
if (Update!=null)
{
Update();
}
}
}
//订阅者
class PlayObServer
{
private string name;
private ISubject sub;//定义一个抽象发布者的引用
public PlayObServer(string name,ISubject sub)
{
this.name = name;
this.sub = sub;
}
//放下手机,假装写代码
public void PlayPhone()
{
Console.WriteLine("{0} {1}放下手机,假装写代码",sub.Subject,name);
}
}
class ViewObServer
{
private string name;
private ISubject sub;//定义一个抽象发布者的引用
public ViewObServer(string name, ISubject sub)
{
this.name = name;
this.sub = sub;
}
public void WatchVIew()
{
Console.WriteLine("{0} {1}关闭窗口,假装写代码", sub.Subject, name);
}
}
class Client
{
static int Main(string[] args)
{
//初始化老师
Teacher Liwei = new Teacher();
//初始化同学
PlayObServer XiaoMing = new PlayObServer("小明", Liwei);
ViewObServer XiaoHong = new ViewObServer("小红", Liwei);
//监听事件
Liwei.Update += XiaoMing.PlayPhone;
Liwei.Update += XiaoHong.WatchVIew;
//老师来了一条信息
Liwei.Subject = "七点了,老师准备查班啦";
Liwei.Notify();
Console.ReadKey();
return 0;
}
}