觀察者模式(Observer):定義了一種一對多的依賴關系,讓多個觀察者對象同時監聽某一主題對象。這個主題對象在狀態發生變化時,會通知所有觀察者對象,使它們能夠自動更新自己。
{ public 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 observer in observers) { observer.Update(); } } } public abstract class Observer { public abstract void Update(); } public class ConcreteSubject : Subject { private string subjectState; public string SubjectState { get { return subjectState; } set { subjectState = value; } } } public 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); } public ConcreteSubject Subject { get { return subject; } set { subject = value; } } } }View Code
測試代碼:
ConcreteSubject subject = new ConcreteSubject(); subject.Attach(new ConcreteObserver(subject, "X")); subject.Attach(new ConcreteObserver(subject, "Y")); subject.Attach(new ConcreteObserver(subject, "Z")); subject.SubjectState = "ABC"; subject.Notify();View Code
事件委托:
namespace ObserverDesign { public interface ISubject { string SubjectState { get; set; } void Notify(); } public delegate void HandleMessage(); public class ConcreteSubjectA : ISubject { public string SubjectState { get { return action; } set { action = value ; } } private string action; public event HandleMessage Update; public void Notify() { Update(); } } public class ConcreteSubjectB : ISubject { public string SubjectState { get { return action; } set { action = value; } } private string action; public event EventHandler Update; public void Notify() { Update(); } } public class ObserverA { private string name; private ISubject sub; public ObserverA(string name,ISubject sub) { this.name = name; this.sub = sub; } public void MethodA() { Console.WriteLine("A doing..."); } } public class ObserverB { private string name; private ISubject sub; public ObserverB(string name, ISubject sub) { this.name = name; this.sub = sub; } public void MethodB() { Console.WriteLine("B doing..."); } } }View Code
委托測試代碼:
ConcreteSubjectA subject = new ConcreteSubjectA(); ObserverA oa = new ObserverA("A", subject); ObserverB ob = new ObserverB("B", subject); subject.Update += new HandleMessage(oa.MethodA); subject.Update += new HandleMessage(ob.MethodB); subject.SubjectState = "start..."; subject.Notify();View Code