定 义:定义了一种一对多的依赖关系,让多个观察者对象同时监听某一主题对象。这个主题对象在状态发生
变化时,会通知所有观察者对象,使他们能够自动更新自己。
结构图:
抽象主题类:
abstract class Subject
{
private IList<Observer> observers = new List<Observer>(); /// <summary>
/// 增加观察者
/// </summary>
/// <param name="observer"></param>
public void Attach(Observer observer)
{
observers.Add(observer);
} /// <summary>
/// 移除观察者
/// </summary>
/// <param name="observer"></param>
public void Detach(Observer observer)
{
observers.Remove(observer);
} //通知
public void Notify()
{
foreach (Observer observer in observers)
{
observer.Update();
}
}
}
抽象观察者类:
abstract class Observer
{
public abstract void Update();
}
具体主题类:
class ConcreteSubject : Subject
{
private string subjectState; //具体被观察者状态
public string SubjectState
{
get { return subjectState; }
set { subjectState = value; }
}
}
具体观察者类:
class ConcreteObserver : Observer
{
private string name;
private string observerState;
private ConcreteSubject subject; public ConcreteObserver(ConcreteSubject subject, string name)
{
this.name = name;
this.subject = subject;
} public override void Update()
{
observerState = subject.SubjectState;
Console.WriteLine("观察者{0}的新状态为{1}", name, observerState);
} public ConcreteSubject Subject
{
get { return subject; }
set { subject = value; }
}
}
客户端代码:
ConcreteSubject s = new ConcreteSubject(); s.Attach(new ConcreteObserver(s, "X"));
s.Attach(new ConcreteObserver(s, "Y"));
s.Attach(new ConcreteObserver(s, "Z")); s.SubjectState = "ABC";
s.Notify();