名称 | Observer |
结构 | |
意图 | 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新。 |
适用性 |
|
Code Example |
1// Observer 2 3// Intent: "Define a one-to-many dependency between objects so that when one 4// object changes state, all its dependents are notified and 5// updated automatically". 6 7// For further information, read "Design Patterns", p293, Gamma et al., 8// Addison-Wesley, ISBN:0-201-63361-2 9 10/* Notes: 11 * Often used for Document-View architectures, where a document stores 12 * data and one or more views renders the data. 13 */ 14 15namespace Observer_DesignPattern 16{ 17 using System; 18 using System.Collections; 19 20 class Subject 21 { 22 private ArrayList list = new ArrayList(); 23 24 private string strImportantSubjectData = "Initial"; 25 26 public string ImportantSubjectData 27 { 28 get 29 { 30 return strImportantSubjectData; 31 } 32 set 33 { 34 strImportantSubjectData = value; 35 } 36 } 37 38 public void Attach(Observer o) 39 { 40 list.Add(o); 41 o.ObservedSubject = this; 42 } 43 44 public void Detach(Observer o) 45 { 46 47 } 48 49 public void Notify() 50 { 51 foreach (Observer o in list) 52 { 53 o.Update(); 54 } 55 } 56 } 57 58 class ConcreteSubject : Subject 59 { 60 public void GetState() 61 { 62 63 } 64 65 public void SetState() 66 { 67 68 } 69 } 70 71 abstract class Observer 72 { 73 protected Subject s; 74 public Subject ObservedSubject 75 { 76 get 77 { 78 return s; 79 } 80 set 81 { 82 s = value; 83 } 84 } 85 abstract public void Update(); 86 } 87 88 class ConcreteObserver : Observer 89 { 90 private string observerName; 91 92 public ConcreteObserver(string name) 93 { 94 observerName = name; 95 } 96 97 override public void Update() 98 { 99 Console.WriteLine("In Observer {0}: data from subject = {1}", 100 observerName, s.ImportantSubjectData); 101 } 102 } 103 104 /// <summary> 105 /// Summary description for Client. 106 /// </summary> 107 public class Client 108 { 109 public static int Main(string[] args) 110 { 111 // Set up everything 112 ConcreteSubject s = new ConcreteSubject(); 113 ConcreteObserver o1 = new ConcreteObserver("first observer"); 114 ConcreteObserver o2 = new ConcreteObserver("second observer"); 115 116 s.Attach(o1); 117 s.Attach(o2); 118 119 // make changes to subject 120 s. ImportantSubjectData = "This is important subject data"; 121 122 // Notify all observers 123 s.Notify(); 124 return 0; 125 } 126 } 127} 128 |