标签:send lan eve blank alt people ... sub play
第一种解决方案用事件来解决:是多级的联动:即:猫叫-》老鼠跑-》人醒
1 public class Cat 2 { 3 public delegate void Crying(object sender,EventArgs e);//定义一个猫叫委托 4 public event Crying cry;//定义猫叫事件 5 public void OnCry(EventArgs e) 6 { 7 if(cry!=null) 8 { 9 cry(this,e); 10 } 11 } 12 public void StartCrying()//猫叫、触发cry事件 13 { 14 MessageBox.Show("猫开始叫了......"); 15 EventArgs e=new EventArgs(); 16 OnCry(e); 17 } 18 } 19 20 public class Mouse 21 { 22 public delegate void Runing(Object sender,EventArgs e); 23 public evnet Running run; 24 public void OnRun(EventArgs e) 25 { 26 if(run!=null) 27 { 28 run(this,e); 29 } 30 } 31 public Mouse(Cat c) 32 { 33 c.cry+=new Cat.Crying(c_Cry);//注册了猫叫事件,老鼠听到猫叫则开始逃跑 34 } 35 void c_Cry(object sender,EvnetArgs e)//老鼠在逃跑时又触发了人被惊醒事件 36 { 37 MessageBox.Show("老鼠开始逃跑了........"); 38 EventArgs e=new EventArgs(); 39 OnRun(e); 40 } 41 } 42 public class Person 43 { 44 public Person(Mouse m) 45 { 46 m.run+=new Mouse.Runing(m_run);//人注册了老鼠逃跑事件,老鼠逃跑时人被 惊醒 47 } 48 void m_run(object sender,EventArgs e) 49 { 50 MessageBox.Show("人醒了"); 51 } 52 } 53 54 BtnTest_Click(object sender, EventArgs e) 55 { 56 Cat c=new Cat(); 57 Mouse m=new Mouse(c); 58 Person p=new Person(m); 59 c.StartCrying(); 60 }
第二种解决方案采用观察者模式:猫叫-》老鼠跑;猫叫-》人醒
1 public interface Observer 2 { 3 void Response();//对被观察对象的行为作出反应,这里是指猫叫 4 } 5 public interface Subject 6 { 7 void AddObserver(Observer obj);//添加所有的观察者,在发生动作时对他们进行通知 8 } 9 10 public class Cat:Subject 11 { 12 ArrayList arrlyList; 13 public Cat() 14 { 15 arrlyList=new ArrayList(); 16 } 17 void AddObserver(Observer obj)//实现添加观察着对象的方法 18 { 19 arrlyList.Add(obj); 20 } 21 void Cry()//猫叫了,并通知所有的观察者,作出相应的反应 22 { 23 MessageBox.Show("猫叫了......"); 24 foreach(Observer obj in arrlyList) 25 { 26 obj.Response(); 27 } 28 } 29 } 30 31 public class Mouse:Observer 32 { 33 public Mouse(Cat c)//将当前的观察着对象添加到观察者集合中 34 { 35 c.AddObserver(this); 36 } 37 public void Response() 38 { 39 MessageBox.show("老鼠开始逃跑了....."); 40 } 41 } 42 43 public class People:Observer 44 { 45 public People(Cat c)//将当前的观察着对象添加到观察者集合中 46 { 47 c.AddOberver(this); 48 } 49 public void Respone() 50 { 51 MessageBox.Show("人醒了,What‘s Wrong?"); 52 } 53 } 54 55 Btn_Click(Object sender,EventArgs e) 56 { 57 Cat c=new Cat(); 58 Mouse m=new Mouse(c); 59 People p=new People(c); 60 c.Cry(); 61 }
摘选自:http://www.cnblogs.com/star8521/p/4977912.html
标签:send lan eve blank alt people ... sub play
原文地址:http://www.cnblogs.com/xskblog/p/7481977.html