关于一道题目的讨论

it2026-03-13  6

 

题目如下:

程序设计: 猫大叫一声,所有的老鼠都开始逃跑,主人被惊醒。(C#语言)

要求: 

1.要有联动性,老鼠和主人的行为是被动的。

2.考虑可扩展性,猫的叫声可能引起其他联动效应。

实现方法一:

View Code 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace CatSound2 7 { 8 9 class Cat10 {11 #region 猫叫事件12 public delegate void CatSoundHandler(object sender, EventArgs e); //委托13 14 public event CatSoundHandler CatSound; //事件15 16 protected virtual void OnCatSound(EventArgs e) //触发17 {18 if (CatSound != null)19 CatSound(this, e);20 }21 #endregion22 23 /// <summary>24 /// 猫叫方法25 /// </summary>26 public void Sound() //调用27 {28 Console.WriteLine("猫叫了.");29 OnCatSound(new EventArgs());30 }31 }32 33 class Human34 {35 public string Name { get; set; }36 public Human(string name)37 {38 this.Name = name;39 }40 41 public void Wake()42 {43 Console.WriteLine(string.Format("主人 {0} 醒了.", this.Name));44 }45 }46 47 class Mouse48 {49 public string Name { get; set; }50 public Mouse(string name)51 {52 this.Name = name;53 }54 55 public void Run()56 {57 Console.WriteLine(string.Format("老鼠 {0} 跑了.", this.Name));58 }59 }60 61 class Program62 {63 static void Main(string[] args)64 {65 Cat cat = new Cat();66 Human man = new Human("张先生");67 Human wife = new Human("张太太");68 69 Mouse mouseA = new Mouse("黄黄");70 Mouse mouseB = new Mouse("灰灰");71 72 cat.CatSound += (o, e) =>73 {74 man.Wake(); 75 wife.Wake(); 76 mouseA.Run(); 77 mouseB.Run();78 };79 80 cat.Sound();81 82 Console.ReadLine();83 }84 }85 }

 

实现方法二:

View Code 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace CatSound 7 { 8 interface IAlarmed 9 {10 void Alarmed();11 }12 13 class Cat14 {15 public List<IAlarmed> AlarmedThings;16 17 public Cat()18 {19 this.AlarmedThings = new List<IAlarmed>();20 }21 22 public void Sound()23 {24 Console.WriteLine("猫叫了.");25 foreach (IAlarmed item in this.AlarmedThings)26 {27 item.Alarmed();28 }29 }30 }31 32 class Master : IAlarmed33 {34 public void Wake()35 {36 Console.WriteLine("主人被惊醒!");37 }38 39 public void Alarmed()40 {41 this.Wake();42 }43 }44 45 class Mouse : IAlarmed46 {47 public Mouse(string name)48 {49 this.Name = name;50 }51 public string Name { get; set; }52 53 public void Run()54 {55 Console.WriteLine(string.Format("{0} 跑掉了.", this.Name));56 }57 58 public void Alarmed()59 {60 this.Run();61 }62 }63 64 class Program65 {66 static void Main(string[] args)67 {68 Cat cat = new Cat();69 cat.AlarmedThings.Add(new Mouse("老鼠A"));70 cat.AlarmedThings.Add(new Mouse("老鼠B"));71 cat.AlarmedThings.Add(new Mouse("老鼠C"));72 cat.AlarmedThings.Add(new Master());73 74 cat.Sound();75 Console.Read();76 77 }78 }79 }

 

第一种方法用了事件,第二种方法用了接口, 哪种方法更好, 或者有什么其它更好的方法,希望大家指点。

转载于:https://www.cnblogs.com/davidyang78/archive/2012/03/26/2418330.html

最新回复(0)