观察者模式:一种一对多依赖关系,多个观察者对象同时监听一个对象,这个对象发生改变,会通知所有观察者对象,让他们来更新自己。
1 namespace DesignModel.观察者模式 2 { 3 4 /// <summary> 5 /// 抽象被观察者 6 /// </summary> 7 internal abstract class Source 8 { 9 private IList<AbsObserver> ts = new List<AbsObserver>(); 10 11 internal void Add(AbsObserver abss) 12 { 13 ts.Add(abss); 14 } 15 internal void Remove(AbsObserver abss) 16 { 17 ts.Remove(abss); 18 } 19 20 internal void Notify() 21 { 22 ts.ForEach(t => 23 { 24 t.Update(); 25 }); 26 } 27 } 28 29 /// <summary> 30 /// 具体被观察者 31 /// </summary> 32 class Teacher : Source 33 { 34 public string Name { get; set; } 35 public string TeachWords { get; set; } 36 } 37 38 39 /// <summary> 40 /// 抽象观察者 41 /// </summary> 42 abstract class AbsObserver 43 { 44 public abstract void Update(); 45 46 } 47 /// <summary> 48 /// 观察者 49 /// </summary> 50 class ObserA : AbsObserver 51 { 52 private Teacher Tearcher { get; set; } 53 public string State { get; set; } 54 public ObserA(Teacher t)//观察者与被观察者不得不耦合 55 { 56 Tearcher = t; 57 } 58 public override void Update() 59 { 60 //........do something for 'sync' 61 this.State = Tearcher.TeachWords; 62 } 63 } 64 65 66 67 static class Extends 68 { 69 public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) 70 { 71 foreach (var item in source) 72 { 73 action(item); 74 } 75 } 76 } 77 78 79 } 80 81 static void 观察者模式() 82 { 83 var t = new Teacher(); 84 t.Add(new ObserA(t)); 85 //t.add(new ObserB(t)); 86 //...... 87 t.Name = "Liu"; 88 t.TeachWords = "hello world"; 89 t.Notify(); 90 }