當觀察者發生變化,通過Notify接口通知所有觀察者。避免直接的實現,降低耦合。 [csharp] <span style="font-size:12px;">abstract class Subject { private IList<Observer> observers = new List<Observer >(); //增加觀察者 public void Attach(Observer observer) { observers.Add(observer ); } //移除觀察者 public void Detach(Observer observer) { observers.Remove(observer ); } //通知 public void Notify() { foreach (Observer o in observers) { o.Update(); } } }</span> 抽象觀察者Observers類 當得到主題通知時,調用Update。稱為更新接口 [csharp] <span style="font-size:10px;">abstract class Observer { public abstract void Update(); } abstract class Subject</span> 具體觀察者concreteObserver類 實現抽象觀察者的update接口,更新當前狀態。 [csharp] class ConcreteObserver : Observer { private string name; private string observerState; private ConcreteSubject subject; public ConcreteObserver(ConcreteSubject subject, string name) { this.subject = subject; this.name = name; } public override void Update() { observerState=subject.SubjectState; Console.WriteLine ("觀察者{0}的狀態是{1}",name,observerState ); } } 客戶端 [csharp] static void Main(string[] args) { ConcreteSubject a = new ConcreteSubject(); a.Attach(new ConcreteObserver (a,"b")); a.SubjectState = "狀態a"; a.Notify(); Console.Read(); }