static void Main(string[] args) { //一对多的依赖关系有耦合 Cat cat = new Cat(); cat.Miao_0(); //1.使用面向抽象实现观察者模式。对观察者行为提供接口;主题对象中提供观察者行为接口的集合用来存放观察者引用(订阅);通过遍历观察者行为接口集合触发订阅。 Console.WriteLine("*************Observer***************"); { cat.AddObserver(new Mouse()); cat.AddObserver(new Dog()); cat.AddObserver(new Baby()); cat.MiaoObserver(); } //2.使用Event实现观察者模式。 { Console.WriteLine("*************Event***************"); Baby baby = new Baby(); cat.CatMiaoEvent += new Mouse().Run; cat.CatMiaoEvent += new Dog().Wang; cat.CatMiaoEvent += baby.Cry; cat.MiaoEvent(); cat.CatMiaoEvent -= baby.Cry; cat.MiaoEvent(); } Console.ReadKey(); }
/// <summary> /// 观察者模式例子 /// 背景:猫大叫,两只老鼠开始逃跑,主人醒来,宝宝也醒来了并且哭了起来 /// </summary> /// <param name="args"></param> static void Main(string[] args) { // 定义猫 var myCat = new Cat(); // 定义两只老鼠 var myMouse1 = new Mouse("mouse1", myCat); var myMouse2 = new Mouse("mouse2", myCat); // 定义主人 var myMaster = new Master(myCat); // 定义baby var myBaby = new Baby(myCat); // 猫大叫 myCat.Cry(); Console.Read(); }
static void Main(string[] args) { Console.WriteLine("欢迎大家来到软谋教育.net高级班公开课之设计模式特训课,今天是Eleven老师为大家带来的观察者模式"); Baby bady = new Baby(); bady.Cry(); Console.WriteLine("*************new Cry******************"); bady.AddObserver(new Father()); bady.AddObserver(new Mother()); bady.AddObserver(new Dog()); bady.AddObserver(new Cat()); bady.AddObserver(new Mouse()); bady.AddObserver(new Neighbor()); bady.NewCry(); Console.WriteLine("*************Cry event******************"); bady.BabyCryHandler += new Father().Roar; bady.BabyCryHandler += new Mother().Whisper; bady.BabyCryHandler += new Dog().Bark; bady.BabyCryHandler += new Cat().Run; bady.BabyCryHandler += new Mouse().Hide; bady.BabyCryHandler += new Neighbor().Awake; bady.CryEvent(); Action <string, int, DateTime> action = new Action <string, int, DateTime>(Test); action("天天", 11, DateTime.Now); //Func Console.ReadKey(); }