一,什么是观察者模式(Observer Pattern)?
当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象
二,代码如下:
在一开始我们先定义两个类,一个是Chinese类(被观察者) ,另一个是Jan类(观察者),观察者设计模式是当被观察者状态发生改变,从而触发观察者的事件
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _16.观察者模式 { /// <summary> /// 当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象 /// </summary> class Program { static void Main(string[] args) { Chinese ch = new Chinese("拿着棍子", "穿白色衣服的"); Jan j1 = new Jan("灰衣服", ch); Jan j2 = new Jan("黑衣服", ch); ch.Coming(); //当中国人的状态发生改变,从而触发观察者绑定在中国人身上的事件(Coming) Console.ReadKey(); } } public class Chinese { private string name; private string color; public Chinese(string name, string color) { this.name = name; this.color = color; } /// <summary> /// 中国人过来(中国人的状态发生改变)(被观察者的状态发生改变) /// </summary> public void Coming() { Console.WriteLine(color + "的中国人" + name + "过来了 ..."); if (ActionCome != null) ActionCome(); } public event Action ActionCome; //声明一个事件 发布了一个消息 } class Jan { private string color; public Jan(string color, Chinese cat) { this.color = color; cat.ActionCome += this.RunAway;//把自身的逃跑方法 注册进 中国人Coming事件里面 订阅消息 } /// <summary> /// 逃跑功能 /// </summary> public void RunAway() { Console.WriteLine(color + "的日本人说:赶紧跑"); } } }
三,观察者模式的核心是使用Action将观察者事件绑定到被观察者中,这样我们就可以通过观察者时间异步通知被观察者