观察者模式:通知者定义一个委托,观察者通过将指定的方法监听到委托,以实现对观察者的更新 #region 观察者模式:观察者Mouse將Run方法監聽到Cat的委托Catshout,当委托被执行的时候,mouse对象将会执行Run方法 class Cat { private string name; public Cat() { } public Cat(string namestr) { this.name = namestr; } public delegate void CatShoutHandler(object sender, EventArgs args); public event CatShoutHandler CatShout; public void Shout() { Console.WriteLine("I'M " + name + ",喵"); EventArgs eventArgs = new EventArgs(); eventArgs.Name = name; CatShout(this, eventArgs); } } class EventArgs { private string name; public string Name { set { name = value; } get { return name; } } } class Mouse { private string name; public Mouse() { } public Mouse(string namestr) { this.name = namestr; } public void Run(object sendre, EventArgs args) { Console.WriteLine("貓哥" + args.Name + "來了," + name + "快跑。"); } } #endregion class Program { static void Main(string[] args) { #region 观察者模式调用 Console.WriteLine("观察者模式运行效果:"); Cat catL = new Cat("halo"); Mouse mouse1 = new Mouse("mouse1"); Mouse mouse2 = new Mouse("mouse2"); catL.CatShout += mouse1.Run; catL.CatShout += mouse2.Run; catL.Shout(); #endregion } }