C#经典机试题(猫叫)
猫大叫一声,所有的老鼠都开始逃跑,主人被惊醒。(C#语言)
1.要有联动性,老鼠和主人的行为是被动的。
2.考虑可扩展性,猫的叫声可能引起其他联动效应。
public interface Observer { void Response();//观察者响应 } public interface Subject { void AimAt(Observer obs); //针哪些观察者 } public class Mouse : Observer { private string name; public Mouse(string _name, Subject sub) { this.name = _name; sub.AimAt(this); } public void Response() { Console.WriteLine(name + "开始逃跑..."); } } public class Master : Observer { public Master(Subject sub) { sub.AimAt(this); } public void Response() { Console.WriteLine("主人惊醒..."); } } 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() { Console.WriteLine("猫叫"); foreach (Observer obs in this.observers) { obs.Response(); } } } class Program { static void Main(string[] args) { Cat cat = new Cat(); Mouse mouse1 = new Mouse("老鼠1", cat); Mouse mouse2 = new Mouse("老鼠2", cat); Master master = new Master(cat); cat.Cry(); Console.ReadKey(); } }