标签:
结构 | |
意图 | 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新。 |
适用性 |
|
1 using System; 2 using System.Collections; 3 4 class Subject 5 { 6 private ArrayList list = new ArrayList(); 7 8 private string strImportantSubjectData = "Initial"; 9 10 public string ImportantSubjectData 11 { 12 get 13 { 14 return strImportantSubjectData; 15 } 16 set 17 { 18 strImportantSubjectData = value; 19 } 20 } 21 22 public void Attach(Observer o) 23 { 24 list.Add(o); 25 o.ObservedSubject = this; 26 } 27 28 public void Detach(Observer o) 29 { 30 31 } 32 33 public void Notify() 34 { 35 foreach (Observer o in list) 36 { 37 o.Update(); 38 } 39 } 40 } 41 42 class ConcreteSubject : Subject 43 { 44 public void GetState() 45 { 46 47 } 48 49 public void SetState() 50 { 51 52 } 53 } 54 55 abstract class Observer 56 { 57 protected Subject s; 58 public Subject ObservedSubject 59 { 60 get 61 { 62 return s; 63 } 64 set 65 { 66 s = value; 67 } 68 } 69 abstract public void Update(); 70 } 71 72 class ConcreteObserver : Observer 73 { 74 private string observerName; 75 76 public ConcreteObserver(string name) 77 { 78 observerName = name; 79 } 80 81 override public void Update() 82 { 83 Console.WriteLine("In Observer {0}: data from subject = {1}", 84 observerName, s.ImportantSubjectData); 85 } 86 } 87 88 /// <summary> 89 /// Summary description for Client. 90 /// </summary> 91 public class Client 92 { 93 public static int Main(string[] args) 94 { 95 // Set up everything 96 ConcreteSubject s = new ConcreteSubject(); 97 ConcreteObserver o1 = new ConcreteObserver("first observer"); 98 ConcreteObserver o2 = new ConcreteObserver("second observer"); 99 100 s.Attach(o1); 101 s.Attach(o2); 102 103 // make changes to subject 104 s. ImportantSubjectData = "This is important subject data"; 105 106 // Notify all observers 107 s.Notify(); 108 return 0; 109 } 110 }
标签:
原文地址:http://www.cnblogs.com/ziranquliu/p/4653405.html