观察者模式

观察者模式与组合模式有点像,只是Subject不从Observer接口派生罢了。

 

首先,定义一个接口——这是个任务板,100万悬赏XX人头一枚。

 

 1 /// <summary>
 2 /// 观察者接口。
 3 /// </summary>
 4 public interface IObserver
 5 {
 6     /// <summary>
 7     /// 画图。
 8     /// </summary>
 9     void Draw();
10 }

其次,从接口派生出一个或多个类——这是个左顾右盼的带刀小哥,似乎在寻人。

 

 1 /// <summary>
 2 /// 矩形类。
 3 /// </summary>
 4 public sealed class Square : IObserver
 5 {
 6     private Double _width;      // 宽。
 7     private Double _length;     // 长。
 8     private Polygon _polygon;   // 多边形。
 9 
10     /// <summary>
11     /// 创建 <see cref="Polygon"/> 的新实例。
12     /// </summary>
13     /// <param name="p">多边形实例。</param>
14     public Square(Polygon p)
15     {
16         _polygon = p;
17     }
18 
19     /// <summary>
20     /// 画图。
21     /// </summary>
22     public void Draw()
23     {
24         _width = _polygon.Width;
25         _length = _polygon.Length;
26     }
27 }

然后,定义一个供应者——拉皮条的见到小哥,眼睛一亮,笑道:大爷,来玩呀~

 

 1 /// <summary>
 2 /// 提供者。
 3 /// </summary>
 4 public class Subject
 5 {
 6     // 观察者集合。
 7     private IList<IObserver> _observers = new List<IObserver>();
 8 
 9     /// <summary>
10     /// 注册观察者。
11     /// </summary>
12     /// <param name="o">要注册的观察者。</param>
13     public void RegisterObserver(IObserver o)
14     {
15         _observers.Add(o);
16     }
17 
18     /// <summary>
19     /// 通知观察者。
20     /// </summary>
21     protected void NotifyObservers()
22     {
23         foreach (IObserver o in _observers)
24         {
25             o.Draw();
26         }
27     }
28 }

最后,从供应者派生一个子类——拉皮条的身后站着一人,身形苗条,原来标致小妞。她在默默冲小哥放电。

 

 1 /// <summary>
 2 /// 多边形类。
 3 /// </summary>
 4 public sealed class Polygon : Subject
 5 {
 6     private Double _length; // 长。
 7     private Double _width;  // 宽。
 8 
 9     /// <summary>
10     /// 设置多边形的边长。
11     /// </summary>
12     /// <param name="length">长。</param>
13     /// <param name="width">宽。</param>
14     public void SetPolygon(Double length, Double width)
15     {
16         _length = length;
17         _width = width;
18         NotifyObservers();
19     }
20 
21     /// <summary>
22     /// 获取长度。
23     /// </summary>
24     public Double Length => _length;
25 
26     /// <summary>
27     /// 获取宽度。
28     /// </summary>
29     public Double Width => _width;
30 }

下面省略一万字。

原文地址:https://www.cnblogs.com/yyzj/p/6637224.html