事件委托实现观察者模式
Posted Sunny秋刀鱼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了事件委托实现观察者模式相关的知识,希望对你有一定的参考价值。
Subject 通知者接口:
public interface Subject { void Notify(); string SubjectState { get; set; } }
StockObserver 看股票同事类:
/// <summary> /// 看股票同事类 /// </summary> public class StockObserver { private string name; public string Name { get { return name; } set { name = value; } } private Subject sub; public Subject Sub { get { return sub; } set { sub = value; } } public StockObserver() { } public StockObserver(string name, Subject sub) { this.Name = name; this.Sub = sub; } /// <summary> /// 关闭股票行情 /// </summary> public void CloseStockMarket() { Console.WriteLine("{0} {1}关闭股票行情,继续工作!", Sub.SubjectState, this.Name); } }
NBAObserver 看NBA的同事类:
/// <summary> /// 看NBA的同事类 /// </summary> public class NBAObserver { private string name; public string Name { get { return name; } set { name = value; } } private Subject sub; public Subject Sub { get { return sub; } set { sub = value; } } public NBAObserver() { } public NBAObserver(string name, Subject sub) { this.Name = name; this.Sub = sub; } /// <summary> /// 关闭NBA直播 /// </summary> public void CloseNBADirectSeeding() { Console.WriteLine("{0} {1}关闭NBA直播,继续工作!", Sub.SubjectState, this.Name); } }
声明一无参数,无返回值的委托:
public delegate void EventHandler();
Boss 老板类:
/// <summary> /// 老板类 /// </summary> public class Boss : Subject { //声明一事件Update,类型为委托EventHandler public event EventHandler Update; private string subjectState; public string SubjectState { get { return subjectState; } set { subjectState = value; } } public void Notify() { if (Update!=null) { //调用事件 Update(); } } }
Secretary 秘书类:
/// <summary> /// 秘书类 /// </summary> public class Secretary : Subject { //声明一事件Update,类型为委托EventHandler public event EventHandler Update; private string subjectState; public string SubjectState { get { return subjectState; } set { subjectState = value; } } public void Notify() { if (Update != null) { //调用事件 Update(); } } }
客户端代码:
static void Main(string[] args) { Boss bill = new Boss(); //看股票的同事 StockObserver tongshi1 = new StockObserver("小明", bill); NBAObserver tongshi2 = new NBAObserver("小王", bill); //注册事件 bill.Update += new EventHandler(tongshi1.CloseStockMarket); bill.Update += new EventHandler(tongshi2.CloseNBADirectSeeding); //老板回来 bill.SubjectState = "我比尔回来了!"; //发出通知 bill.Notify(); Console.ReadKey(); }
运行结果如下图:
以上是关于事件委托实现观察者模式的主要内容,如果未能解决你的问题,请参考以下文章
观察者模式实践-实现winform 窗体之间传值(事件实现)
C# 委托和事件 与 观察者模式(发布-订阅模式)讲解 by天命