观察者模式(Observer Pattern): 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
public interface ISubject {
void AddObserver(Observer observer);
void DeleteObserver(Observer observer);
}
public class Subject: ISubject
{
private IList<Observer> _observers = new List<Observer>();
private int _qantity;
public int Qantity
{
get
{
return _qantity;
}
set
{
_qantity = value;
this.NotifyAllObservers();
}
}
public void AddObserver(Observer observer) {
_observers.Add(observer);
}
public void DeleteObserver(Observer observer)
{
_observers.Remove(observer);
}
private void NotifyAllObservers() {
foreach (var observer in _observers) {
observer.Update();
}
}
}
public abstract class Observer
{
protected Subject _subject;
public abstract void Update();
}
public class ObserverA : Observer
{
public override void Update()
{
Console.WriteLine("我是A,我知道你的数量改变了!");
}
}
public class ObserverB : Observer
{
public ObserverB(Subject subject)
{
_subject = subject;
}
public override void Update()
{
Console.WriteLine("我是B,我知道你的数量改变成了"+_subject.Qantity);
}
}
static void Main(string[] args)
{
Subject subject = new Subject();
subject.AddObserver(new ObserverA());
subject.AddObserver(new ObserverB(subject));
subject.Qantity = 10;
Console.ReadLine();
}
源码地址
其他设计模式