貓大叫一聲,所有的老鼠都開始逃跑,主人被驚醒。(C#語言)
阿新 • • 發佈:2019-02-18
程式設計: 貓大叫一聲,所有的老鼠都開始逃跑,主人被驚醒。(C#語言)
要求:
1.要有聯動性,老鼠和主人的行為是被動的。
2.考慮可擴充套件性,貓的叫聲可能引起其他聯動效應。
要點:1. 聯動效果,執行程式碼只要執行Cat.Cryed()方法。2. 對老鼠和主人進行抽象
評分標準: <1>.構造出Cat、Mouse、Master三個類,並能使程式執行(2分)
<2>從Mouse和Master中提取抽象(5分)
<3>聯動效應,只要執行Cat.Cryed()就可以使老鼠逃跑,主人驚醒。(3分)
2 {
3 void Response(); //觀察者的響應,如是老鼠見到貓的反映
4 }
5 public interface Subject
6 {
7 void AimAt(Observer obs); //針對哪些觀察者,這裡指貓的要撲捉的物件---老鼠
8 }
9 public class Mouse : Observer
10 {
11 private string name;
12 public Mouse(string name, Subject subj)
13 {
14 this.name = name;
15 subj.AimAt(this);
16 }
17
18 public void Response()
19 {
20 Console.WriteLine(name + " attempt to escape!");
21 }
22 }
23 public class Master : Observer
24 {
25 public Master(Subject subj)
26 {
27 subj.AimAt(this);
28 }
29
30 public void Response()
31 {
32 Console.WriteLine("Host waken!");
33 }
34 }
35
36 public class Cat : Subject
37 {
38 private ArrayList observers;
39 public Cat()
40 {
41 this.observers = new ArrayList();
42 }
43 public void AimAt(Observer obs)
44 {
45 this.observers.Add(obs);
46 }
47 public void Cry()
48 {
49 Console.WriteLine("Cat cryed!");
50 foreach (Observer obs in this.observers)
51 {
52 obs.Response();
53 }
54 }
55 }
56 class MainClass
57 {
58 static void Main(string[] args)
59 {
60 Cat cat = new Cat();
61 Mouse mouse1 = new Mouse("mouse1", cat);
62 Mouse mouse2 = new Mouse("mouse2", cat);
63 Master master = new Master(cat);
64 cat.Cry();
65 }
66 }
67
68
69 //---------------------------------------------------------------------------------------------
70
71 設計方法二: 使用event -- delegate設計..
72 public delegate void SubEventHandler();
73 public abstract class Subject
74 {
75 public event SubEventHandler SubEvent;
76 protected void FireAway()
77 {
78 if (this.SubEvent != null)
79 this.SubEvent();
80 }
81 }
82 public class Cat : Subject
83 {
84 public void Cry()
85 {
86 Console.WriteLine("cat cryed.");
87 this.FireAway();
88 }
89 }
90 public abstract class Observer
91 {
92 public Observer(Subject sub)
93 {
94 sub.SubEvent += new SubEventHandler(Response);
95 }
96 public abstract void Response();
97 }
98 public class Mouse : Observer
99 {
100 private string name;
101 public Mouse(string name, Subject sub) : base(sub)
102 {
103 this.name = name;
104 }
105 public override void Response()
106 {
107 Console.WriteLine(name + " attempt to escape!");
108 }
109 }
110 public class Master : Observer
111 {
112 public Master(Subject sub) : base(sub){}
113 public override void Response()
114 {
115 Console.WriteLine("host waken");
116 }
117 }
118 class Class1
119 {
120 static void Main(string[] args)
121 {
122 Cat cat = new Cat();
123 Mouse mouse1 = new Mouse("mouse1", cat);
124 Mouse mouse2 = new Mouse("mouse2", cat);
125 Master master = new Master(cat);
126 cat.Cry();
127 }
128
129 }