拿貓和老鼠的案例來說,代碼如下:
1 定義貓類:
class Cat
{
private string name; private string color;
public Cat(string name,string color)
{
this.name = name; this.color = color;
}
public Action CatDelegate; //定義委托
//模拟貓狀态發生改變
public void CatComing()
{
Console.WriteLine(color+"的貓"+name+"過來了");
if (CatDelegate!=null)
{
CatDelegate();
}
}
//每當觀察者做修改,都在被觀察者裡有變化,增大了代碼的耦合性 摒棄
public void CatComingTwo(Mouse mouse1,Mouse mouse2)
{
mouse1.Run();
mouse2.Run();
}
}
2 定義老鼠類:
class Mouse
{
private string name; private string color;
public Mouse(string name, string color)
{
this.name = name;
this.color = color;
}
public void Run()
{
Console.WriteLine(color+"的老鼠"+name+"跑了");
}
}
3
/// <summary>
/// 使用多點傳播委托實作觀察者模式
/// </summary>
class Program
{
static void Main(string[] args)
{
Cat cat = new Cat("Tom","藍");
Mouse mouse1 = new Mouse("Jerry", "黃");
Mouse mouse2 = new Mouse("Petty", "黑");
//多點傳播委托
cat.CatDelegate += mouse1.Run;//注冊
cat.CatDelegate += mouse2.Run;
cat.CatComing();
Console.ReadKey();
//非委托方式實作,
cat.CatComingTwo(mouse1, mouse2);
}
}
由此可以看出,在不使用委托方式時,當我們增加了一個老鼠,需要在被觀察者的代碼裡增加參數,修改被觀察者的代碼;而使用多點傳播委托實作觀察者模式,被觀察者代碼無需改變,當觀察者做改變,隻需要在委托裡注冊一下即可