using System; using System.Collections.Generic; using System.Text; using System.Collections; ///Observer(观察者)模式又被称作发布-订阅(Publish-Subscribe)模式,用于定义对象间的一对多的依赖关系, ///当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。 ///add by jzh 2007-04-15 namespace DesignPattern { class Subject { private ArrayList list = new ArrayList(); private string strImportantSubjectData = "Initial"; public string ImportantSubjectData { get { return strImportantSubjectData; } set { strImportantSubjectData = value; } } public void Attach(Observer o) { list.Add(o); o.ObservedSubject = this; } public void Detach(Observer o) { } public void Notify() { foreach (Observer o in list) { o.Update(); } } } class ConcreteSubject : Subject { public void GetState() { } public void SetState() { } } abstract class Observer { protected Subject s; public Subject ObservedSubject { get { return s; } set { s = value; } } abstract public void Update(); } class ConcreteObserver : Observer { private string observerName; public ConcreteObserver(string name) { observerName = name; } override public void Update() { Console.WriteLine("观察者 {0}: 消息 = {1}", observerName, s.ImportantSubjectData); } } public class Client { public static void Main(string[] args) { // 建立观察者 ConcreteSubject s = new ConcreteSubject(); ConcreteObserver o1 = new ConcreteObserver("a"); ConcreteObserver o2 = new ConcreteObserver("b"); s.Attach(o1); s.Attach(o2); // 发生变化 s.ImportantSubjectData = "有一条新消息"; // 通知观察者 s.Notify(); Console.ReadLine(); } } }