写了个大概的例子using System;class 例子 { static void Main(string[] args) { Cat c = new Cat(); Owner o = new Owner(); Rat r = new Rat(); c.Handler += new CatShoutingEventHandler(o.OnCatShouting); c.Handler += new CatShoutingEventHandler(r.OnCatShouting); c.Shout(); Console.Read(); } }public delegate void CatShoutingEventHandler();class Cat { public CatShoutingEventHandler Handler; public void Shout() { Handler(); } }class Owner { public void OnCatShouting() { Console.WriteLine("死猫不要叫了"); } }class Rat { public void OnCatShouting() { Console.WriteLine("猫来了,我3"); } }
namespace test { public delegate void Call(); public class cat { public event Call OnCall; public Cat() { Console.Write("Cat Call....."); } public void virtual Call() { if(OnCall;!=null) { this.OnCall;(); } }
} public class Master { public Master(Cat cat) { cat.OnCall +=new Call(Master_WakeUp); } public void Master_WakeUp() { Consloe.Write("Master WakeUp...."); } } public class Mouse { public Mouse(Cat cat) { cat.OnCall +=new Call(Mouse_Run); } public void Mouse_Run() { Console.Write("Mouse Run..."); } }
{
static void Main(string[] args)
{
Cat c = new Cat();
Owner o = new Owner();
Rat r = new Rat();
c.Handler += new CatShoutingEventHandler(o.OnCatShouting);
c.Handler += new CatShoutingEventHandler(r.OnCatShouting);
c.Shout();
Console.Read();
}
}public delegate void CatShoutingEventHandler();class Cat
{
public CatShoutingEventHandler Handler; public void Shout()
{
Handler();
}
}class Owner
{
public void OnCatShouting()
{
Console.WriteLine("死猫不要叫了");
}
}class Rat
{
public void OnCatShouting()
{
Console.WriteLine("猫来了,我3");
}
}
说说我第想到的第一个思路,定义一个接口,里面一个方法,对应于猫叫的时候 ,
定义多个对象(老鼠,人,etc...),都完成那个接口
然后在猫这个对象上添加受影响的对象,最后猫叫的时候更新各个对象的状态...猫相当于观察者,呵呵~~
{
public delegate void Call();
public class cat
{
public event Call OnCall;
public Cat()
{
Console.Write("Cat Call.....");
}
public void virtual Call()
{
if(OnCall;!=null)
{
this.OnCall;();
}
}
}
public class Master
{
public Master(Cat cat)
{
cat.OnCall +=new Call(Master_WakeUp);
}
public void Master_WakeUp()
{
Consloe.Write("Master WakeUp....");
}
}
public class Mouse
{
public Mouse(Cat cat)
{
cat.OnCall +=new Call(Mouse_Run);
}
public void Mouse_Run()
{
Console.Write("Mouse Run...");
}
}
}