"猫叫,老鼠跑,主人被惊醒",要求用C#实现.
园子里已经有不少的朋友都实现了.具体的方法通过观察者模式或者事件来实现.
我这里先摘录一下观察者模式的实现,代码如下:
1 namespace 猫叫
2 {
3 //猫叫,老鼠跑,主人惊醒
4 //使用观察者模式
5 //step1 抽象观察者
6 public interface Observer
7 {
8 void Response(); //接收到事件后作出反应
9 }
10 //step2 抽象引发观察者反应的主对象(猫)
11 public interface Subject
12 {
13 void AimAt(Observer ob); //猫叫后将作用的对象
14 }
15 //抽象老鼠和主人
16 public class Mouse:Observer
17 {
18 private string name;
19 public Mouse(string name,Subject sub) //在构造函数中添加对Subject对象的观察(这里观察猫)
20 {
21 this.name = name;
22 sub.AimAt(this);
23 }
24 public void Response()
25 {
26 Console.WriteLine("Cat Cryed," + name + " run!");
27 }
28 }
29 public class Master:Observer
30 {
31 private string name;
32 public Master(string name, Subject sub)//在构造函数中添加对Subject对象的观察(这里观察猫)
33 {
34 this.name = name;
35 sub.AimAt(this);
36 }
37 public void Response()
38 {
39 Console.WriteLine("Cat cryed ," + name + " is weakup!");
40 }
41 }
42 public class Cat:Subject
43 {
44 private List<Observer> obs;
45 public Cat()
46 {
47 this.obs = new List<Observer>();
48 }
49 public void AimAt(Observer ob)
50 {
51 this.obs.Add(ob);
52 }
53 public void Cry()
54 {
55 foreach(Observer ob in this.obs)
56 {
57 ob.Response();
58 }
59 }
60 }
61 class Program
62 {
63 static void Main(string[] args)
64 {
65 Cat cat=new Cat();
66 Mouse mouse1 = new Mouse("mouse1", cat);
67 Mouse mouse2 = new Mouse("mouse2", cat);
68 Master master = new Master("Xu", cat);
69 cat.Cry();
70 Console.ReadLine();
71 }
72 }
73 }
抽象----所有设计模式的精髓.
2 {
3 //猫叫,老鼠跑,主人惊醒
4 //使用观察者模式
5 //step1 抽象观察者
6 public interface Observer
7 {
8 void Response(); //接收到事件后作出反应
9 }
10 //step2 抽象引发观察者反应的主对象(猫)
11 public interface Subject
12 {
13 void AimAt(Observer ob); //猫叫后将作用的对象
14 }
15 //抽象老鼠和主人
16 public class Mouse:Observer
17 {
18 private string name;
19 public Mouse(string name,Subject sub) //在构造函数中添加对Subject对象的观察(这里观察猫)
20 {
21 this.name = name;
22 sub.AimAt(this);
23 }
24 public void Response()
25 {
26 Console.WriteLine("Cat Cryed," + name + " run!");
27 }
28 }
29 public class Master:Observer
30 {
31 private string name;
32 public Master(string name, Subject sub)//在构造函数中添加对Subject对象的观察(这里观察猫)
33 {
34 this.name = name;
35 sub.AimAt(this);
36 }
37 public void Response()
38 {
39 Console.WriteLine("Cat cryed ," + name + " is weakup!");
40 }
41 }
42 public class Cat:Subject
43 {
44 private List<Observer> obs;
45 public Cat()
46 {
47 this.obs = new List<Observer>();
48 }
49 public void AimAt(Observer ob)
50 {
51 this.obs.Add(ob);
52 }
53 public void Cry()
54 {
55 foreach(Observer ob in this.obs)
56 {
57 ob.Response();
58 }
59 }
60 }
61 class Program
62 {
63 static void Main(string[] args)
64 {
65 Cat cat=new Cat();
66 Mouse mouse1 = new Mouse("mouse1", cat);
67 Mouse mouse2 = new Mouse("mouse2", cat);
68 Master master = new Master("Xu", cat);
69 cat.Cry();
70 Console.ReadLine();
71 }
72 }
73 }
抽象----所有设计模式的精髓.