观察者模式:定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主体对象,这个主题对象在状态发生变化时,会通知所有观察者。当一个对象改变需要同时改变其他对象,而且他不知道具体有多少对象需要改变的时候,应该考虑使用观察者模式。
Define a one-to-many dependency between objects so that when one objects changes state,all its dependents are notified and updated automatically.
观察者结构图:代码:
public abstract class Subject { private IListobservers = new List (); 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(); } } } 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 ConcreteSubject Subject { get { return subject; } set { subject = value; } } 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); } }
引用:
ConcreteSubject c = new ConcreteSubject(); c.Attach(new ConcreteObserver(c, "A")); c.Attach(new ConcreteObserver(c, "b")); c.Attach(new ConcreteObserver(c, "z")); c.SubjectState = "ABC"; c.Notify();
效果