void Main() { Subject s = new Subject(); s.Add(new ObserverA(s)); s.Add(new ObserverB(s)); s.Notify(); } class Subject { List<Observer> observers = new List<Observer>(); public void Add(Observer o){ observers.Add(o);} public void Remove(Observer o){ observers.Remove(o);} public void Notify(){ foreach (var observer in observers) { observer.Show(); } } } abstract class Observer{ protected Subject subject; public Observer(Subject s){ subject = s; } public abstract void Show(); } class ObserverA:Observer{ public ObserverA(Subject s):base(s){} public override void Show(){} } class ObserverB:Observer{ public ObserverB(Subject s):base(s){} public override void Show(){} }
时间: 2024-12-28 21:23:41