观察者模式(Observer Pattern):定义对象之间的一种一对多依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象皆得到通知并被自动更新。观察者模式的别名包括发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。
模式角色与结构:
示例代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharp.DesignPattern.ObserverPattern { class Program { static void Main(string[] args) { Subject subject = new ConcreteSubject(); IObserver player1 = new ConcreteObserver(); IObserver player2 = new ConcreteObserver(); IObserver player3 = new ConcreteObserver(); IObserver player4 = new ConcreteObserver(); subject.Attach(player1); subject.Attach(player2); subject.Attach(player3); subject.Attach(player4); player1.BeAttacked(subject); } } abstract class Subject { protected List<IObserver> observers = new List<IObserver>(); public void Attach(IObserver observer) { observers.Add(observer); } public void Detach(IObserver observer) { observers.Remove(observer); } public abstract void Notify(); } class ConcreteSubject : Subject { public void Notify() { foreach (IObserver observer in observers) { observer.Update(); } } } interface IObserver { public void Update(); public void BeAttacked(Subject subject); } class ConcreteObserver : IObserver { public void Update() { // To do the concrete } public void BeAttacked(Subject subject) { subject.Notify(); } } }