在这个服务为上的社会里面,怎么可能有“强权”的存在?再看看利用委托实现牛奶和报纸的订阅来解决上面的问题:使用委托让牛奶报纸共享箱子。
using System;
namespace myDelegate
...{
public delegate void SendableDelegate(string s);
public class Subscriber
...{
public string name;
public Subscriber(string name)
...{
this.name = name;
}
public void PutNewsPaperIn(string s)
...{
Console.WriteLine("{0}在报箱里收到送来的{1}", name, s);
}
public void PutMilkIn(string s)
...{
Console.WriteLine("{0}在奶箱里收到送来的{1}", name, s);
}
}
public class NewsPaperSender
...{
//委托实现
public event SendableDelegate SendNewsPaperHandler;
public void SendNewsPaper()
...{
if (SendNewsPaperHandler != null)
SendNewsPaperHandler("报纸");
}
public void Subscribe(SendableDelegate sd)
...{
SendNewsPaperHandler += sd;
}
}
public class MilkSender
...{
//委托实现
public event SendableDelegate SendMilkHandler;
public void SendMilk()
...{
if (SendMilkHandler != null)
SendMilkHandler("牛奶"); //事件调用时带参数
}
public void Subscribe(SendableDelegate sd)
...{
SendMilkHandler += sd;
}
}
//功能的实现
public class Client
...{
public static void Main( string[] args )
...{
//委托实现
MilkSender ms = new MilkSender();
NewsPaperSender nps = new NewsPaperSender();
Subscriber s1 = new Subscriber("张三");
Subscriber s2 = new Subscriber("李四");
Subscriber s3 = new Subscriber("王五");
ms.Subscribe(new SendableDelegate(s1.PutMilkIn));
ms.Subscribe(new SendableDelegate(s2.PutMilkIn));
nps.Subscribe(new SendableDelegate(s2.PutNewsPaperIn));
nps.Subscribe(new SendableDelegate(s3.PutMilkIn));
ms.SendMilk();
nps.SendNewsPaper();
}
}
}