观察着设计模式
经典案例:猫叫了,惊动老鼠 和 主人;
第一种利用面向对象的实现方式,分别使用接口和对接口的实现,也就是多肽的特性来进行拓展;
public interface Observer { void Response(); //观察者的响应,如是老鼠见到猫的反映 } public interface Subject { void Aimed(Observer obs); //针对哪些观察者 } public class Mouse : Observer { private string name; public Mouse(string name, Subject sub) { this.name = name; sub.Aimed(this); } public void Response() { Console.WriteLine(name+"attemp to escaped"); } } public class Master : Observer { public Master(Subject sub) { sub.Aimed(this); } public void Response() { Console.WriteLine("host waked"); } } public class Cat : Subject { private ArrayList objservers; public Cat() { this.objservers = new ArrayList(); } public void Aimed(Observer ob) { this.objservers.Add(ob); } public void Cry() { Console.WriteLine("Cat Cryed"); foreach (Observer o in this.objservers) { o.Response(); //接口的好处 ,面向我们的接口编程,具体的实现,交给我们的实际的实现类的方法滴哎呦; } } } public class Test { static void fuck() { Cat cat = new Cat(); Mouse m = new Mouse("nouse1",cat); Mouse m2 = new Mouse("nouse2", cat); Master ma = new Master(cat); cat.Cry(); } }
总之是感觉非常秒的代码滴呀;效果是非常好滴呀;
第二种模式是使用我们委托和事件的特性来进行拓展;
这种方式里面也包含了面向对象的特性滴呀;
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication4 { //这里是对应的我们的第二种实现的方式; public delegate void SubEventHanlder(); public abstract class Subject { public event SubEventHanlder subEvent; protected void FireAway() { if (this.subEvent != null) this.subEvent(); } } public class Cat : Subject { public void Cry() { Console.WriteLine("cat cryed"); this.FireAway(); } } public abstract class Observer { public Observer(Subject sub) { sub.subEvent += new SubEventHanlder(Response); } public abstract void Response(); } public class Mouse : Observer { private string name; public Mouse(string name, Subject sub) : base(sub) { this.name = name; } public override void Response() { Console.WriteLine(name + "attemp to escape!"); } } public class Master : Observer { public Master(Subject sub) : base(sub) { } public override void Response() { Console.WriteLine("host waked"); } } public class Test { public void t() { Cat c = new Cat(); Mouse m1 = new Mouse("m1", c); Mouse m2 = new Mouse("m2", c); Master m = new Master(c); c.Cry(); } } }
后面我们再看看以前,一篇关于烧开水的 观察模式额实例
那个实例也是比较经典滴呀;效果非常好滴呀;
时间: 2024-10-14 08:12:08