定义了一种一对多的依赖关系,当一个对象的状态发生改变时,其所有依赖者都会收到通知并自动更新。
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| abstract class Subject { private IList<Observer> observers = new List<Observer>(); public void Attach(Observer observer) { observers.Add(observer); } public void Detach(Observer observer) { observers.Remove(observer); } public void Notify() { observers.Foreach(o => o.Update()) } }
interface class IObserver { void Update(); }
class ConcreateSubject : Subject { private string subjectState; public string SubjectState { get{return subjectState;} set{subjectState = value} } }
class ConcreatObserver : IObserver { private string name; private string observerState; private ConcreateSubject subject; public ConcreatObserver(ConcreateSubject subject, string name) { this.subject = subject; this.name = name; } public void Update() { observerState = subject.SubjectState; Console.WriteLine("观察者{0}的新状态是{1}", name, observerState); } public ConcreateSubject Subject { get{return subject;} set{subject = value;} } }
ConcreateSubject subject = new ConcreateSubject();l subject.Attach(new ConcreatObserver(subject, "X")); subject.Attach(new ConcreatObserver(subject, "Y")); subject.Attach(new ConcreatObserver(subject, "Z")); subject.SubjectState = "ABC"; subject.Notify();
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
interface Subject { void Noticy(); string SubjectState { get; set; } }
class ConcreateSubject : Subject { public event EventHandler Update; private string action; public void Notify() { Update(); } public string SubjectState { get{return action;} set{action = value;} } }
class ConcreatObserver1 { private string name; private Subject subject; public ConcreatObserver1(Subject subject, string name) { this.subject = subject; this.name = name; } public void Update1() { observerState = subject.SubjectState; Console.WriteLine("观察者{0}的新状态是{1}", name, observerState); } } class ConcreatObserver2 { private string name; private Subject subject; public ConcreatObserver2(Subject subject, string name) { this.subject = subject; this.name = name; } public void Update2() { observerState = subject.SubjectState; Console.WriteLine("观察者{0}的新状态是{1}", name, observerState); } }
ConcreateSubject subject = new ConcreateSubject(); subject.Update += new EventHandler(new ConcreatObserver1(subject, "X").Update1()); subject.Update += new EventHandler(new ConcreatObserver2(subject, "Y").Update2()); subject.SubjectState = "ABC"; subject.Notify();
|