面试题:猫叫了,所有老鼠开始逃跑,主人被惊醒 请用OO思想描述此过程
1.老鼠跟主人是被动的
2.考虑联动性与扩展性。
自己的代码:(参考大话设计模式——观察者模式——程杰)
class Program { static void Main(string[] args) { Cat cat = new Cat(); Mouse m1 = new Mouse("老鼠1"); Mouse m2 = new Mouse("老鼠2"); Master m = new Master(); cat.update +=new EventHandler(m1.Run); cat.update+=new EventHandler(m2.Run); cat.update+= new EventHandler(m.WakeUp); cat.Crew(); Console.Read(); } } /// <summary> /// 通知者接口 /// </summary> interface Subject { void notify(); //string SubjectState { get; set; } } delegate void EventHandler(); /// <summary> /// 猫类 /// </summary> class Cat:Subject { public event EventHandler update; public void Crew() { Console.WriteLine("猫开始大叫"); notify(); } public void notify() { update(); } } /// <summary> /// 老鼠类 /// </summary> class Mouse { public Mouse(string Name) { this.name = Name; } private string name{get;set;} public void Run() { Console.WriteLine(name+"开始逃跑"); } } /// <summary> /// 主人类 /// </summary> class Master { public void WakeUp() { Console.WriteLine("主人醒来"); } }