观察者模式
1. 上图
2. 代码实现
//首先创建一个接口
1 interface IShow 2 { 3 void MyShow(); 4 }
//创建观察者....
1 class C1:IShow 2 { 3 public void MyShow() 4 { 5 Console.WriteLine("我是观察1"); 6 } 7 }
1 static void Main(string[] args) 2 { 3 List<IShow> list = new List<IShow>(); 4 5 IShow userShow = null; 6 7 Assembly assembly = Assembly.Load("观察者模式"); 8 Type[] types = assembly.GetTypes(); 9 10 foreach (var t in types) 11 { 12 if (t.GetInterface("IShow") != null) 13 { 14 userShow = (IShow)Activator.CreateInstance(t); 15 16 list.Add(userShow); 17 } 18 } 19 20 21 foreach (var s in list) 22 { 23 s.MyShow(); 24 } 25 26 Console.ReadKey(); 27 28 }
// 用到了反射的机制,把实现接口IShow都加入到集合中, 这样添加新的观察者就不用修改代码了..
3. 结果
ok ...