观察者模式(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; } } } }
测试代码:
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();
事件委托:
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..."); } } }
委托测试代码:
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();