观察者模式:定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题的对象。这个主体对象在状态发生变化时。会通知所有观察者对象,使他们能够更新自己。
即:一个抽象模型有两个方面,其中一方面依赖于另一方面。这时用观察者模式可以将这两者封装在独立的对象中是他们各自独立的改变和复用。观察者模式主要是解除耦合
体现依赖倒转原则:依赖于接口或抽象,不依赖细节。细节依赖抽象和接口
通知者接口类(Subject):
namespace Observer_Pattern.CLASS { interface Subject { void Attach(Observer observer); //附加 void Detach(Observer observer); //分离 void Notify(); //通知 string SubjectState { get; set; } } }
秘书类(Secreter):继承于通知者接口类(Subject)。实现接口
namespace Observer_Pattern.CLASS { class Secretary:Subject { private IList<Observer> observers = new List<Observer>(); private string action; /// <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); } /// <summary> /// 通知 /// </summary> public void Notify() { foreach (Observer ob in observers) { ob.Update(); } } public string SubjectState { get { return action; } set { action = value; } } } }
观察者抽象类(Observer):
namespace Observer_Pattern.CLASS { abstract class Observer { protected string name; protected Subject sub; public Observer(string name, Subject sub) { this.name = name; this.sub = sub; } public abstract void Update(); } }
炒股的工作者(StockObserver)继承于观察者抽象类(Observer):
namespace Observer_Pattern.CLASS { class StockObserver:Observer { public StockObserver(string name, Subject sub) : base(name, sub) { } public override void Update() { Console.WriteLine("{0} ,{1} 关闭股票软件,继续工作!",sub.SubjectState,name); } } }
看NBA的工作者(NBAObserver)继承于观察者抽象类(Observer):
namespace Observer_Pattern.CLASS { class NBAObserver:Observer { public NBAObserver(string name, Subject sub) : base(name, sub) { } public override void Update() { Console.WriteLine("{0} ,{1} 关闭NBA视频,继续工作!",sub.SubjectState,name); } } }
测试类(TestMain):
namespace Observer_Pattern { class TestMain { static void Main(string[] args) { Secretary mishu = new Secretary(); StockObserver worker1 = new StockObserver("小张",mishu); NBAObserver worker2 = new NBAObserver("小李",mishu); mishu.Attach(worker1); mishu.Attach(worker2); mishu.Detach(worker2); mishu.SubjectState = "老板回来了"; mishu.Notify(); Console.ReadLine(); } } }