题目:程序设计:锚大叫一声,所有的老鼠开始逃跑,主人被惊醒
要求:一:要具有联动性,老鼠和主人的行为是被动的.二:要具有可扩展性,猫的叫声还可能引起其他联动效应
第一种方法:
public interface Observer { void Response(); } public interface Subject { void AimAt(Observer obs); } public class Mouse : Observer { private string name; public Mouse(string name, Subject subj) { this.name = name; subj.AimAt(this); } public void Response() { Console.WriteLine(name + " try to escape"); } } public class Masrer : Observer { public Masrer(Subject sub ) { sub.AimAt(this); } public void Response() { Console.WriteLine("Master waken"); } } public class Cat : Subject { private ArrayList observers; public Cat() { this.observers = new ArrayList(); } public void AimAt(Observer obs) { this.observers.Add(obs); } public void Cry() { foreach (Observer obs in observers) { obs.Response(); } } }
主程序内部:
Cat cat = new Cat(); Mouse mouse1 = new Mouse("mouse1", cat); Mouse mouse2 = new Mouse("mouse2", cat); Masrer master = new Masrer(cat); cat.Cry();
第二种方法:
public delegate void SubeventHandler(); public abstract class Subject { public event SubeventHandler subevent; public void FireAway() { if (this.subevent != null) { this.subevent(); } } } public class Cat : Subject { public void Cry() { Console.WriteLine("Cat begun to cry"); FireAway(); } } public class Mouse : Observer { private string name; public Mouse(string name, Subject sub) : base(sub) { this.name = name; } public override void Response() { Console.WriteLine(this.name + " attempe to run"); } } public abstract class Observer { public Observer(Subject sub) { sub.subevent+=new SubeventHandler(Response); } public abstract void Response(); } public class Master : Observer { public Master(Subject sub):base(sub) { } public override void Response() { Console.WriteLine("Host waken"); } }
event-delegate设计