C# 观察者模式

一、定义

  观察者模式(Observer Pattern)是设计模式中行为模式的一种,它解决了上述具有一对多依赖关系的对象的重用问题。此模式的参与者分为两大类,一类是被观察的目标,另一类是观察该目标的观察者们。正因为该模式是基于“一对多”的关系,所以该模式一般是应用于由一个目标对象和N个观察者对象组成(当然也可以扩展为有多个目标对象,但我们现在只讨论前者)的场合。当目标对象的状态发生改变或做出某种行为时,正在观察该目标对象的观察者们将自动地、连锁地作出相应的响应行为。

二、测试事例

  猫来了,老鼠走了。

  其中猫为被观察的目标,老鼠为观察者,当猫来了行为发生时,老鼠们会做出逃跑的响应行为。

1. 猫和老鼠封装类

 1 class Cat
 2 {
 3     private string name;
 4     private string color;
 5 
 6     public Cat(string name, string color)
 7     {
 8         this.name = name;
 9         this.color = color;
10     }
11 
12     /// <summary>
13     /// 猫进屋(猫的状态发生改变)
14     /// </summary>
15     public void CatComing()
16     {
17         Console.WriteLine("猫来了");
18 
19         if (catCome != null)
20             catCome();
21     }
22     public Action catCome;              // 委托
23 }
 1 class Mouse
 2     {
 3         private string name;
 4         private string color;
 5 
 6         public Mouse(string name, string color)
 7         {
 8             this.name = name;
 9             this.color = color;
10         }
11 
12         /// <summary>
13         /// 逃跑功能
14         /// </summary>
15         public void RunAway()
16         {
17             Console.WriteLine(color + "的老鼠" + name + "跑了");
18         }
19     }

2. 测试代码

 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5           
 6 
 7         Cat cat = new Cat("加菲猫", "黄色");
 8         Mouse mouse1=new Mouse("米奇","黑色");
 9         Mouse mouse2 = new Mouse("唐老鸭", "红色");
10 
11         cat.catCome += mouse1.RunAway;      // 多播委托
12         cat.catCome += mouse2.RunAway;
13 
14         cat.CatComing();            // 猫的状态发生变化
15 
16         //多一只老鼠,不应该修改猫的类。 
17         Console.ReadKey();
18         
19     }
20 }

3. 运行截图 

三、适用场景

  1. 当对一个对象的改变需要同时改变其他对象,而又不知道具体有多少对象有待改变的情况下。
  2. 当一个对象必须通知其他对象,而又不能假定其他对象是谁的情况下。
原文地址:https://www.cnblogs.com/coderJiebao/p/CSharp04.html