这Subscriber代码可以如下
public class DisplayClock
{
public void Subscribe(Clock theClock)
{
theClock.TimeChange += new Clock.TimeInfoHandler(TimeHasChanged);
}
public void TimeHasChanged(object theClock, TimeInfoEventArgs ti)
{
Console.WriteLine("Current Time: {0}:{1}:{2}", ti.hour.ToString(), ti.minute.ToString(), ti.second.ToString());
}
}
DisplayClock dc = new DisplayClock();
dc.Subscribe(theClock);
event关键字在event programming中特别有用
public delegate void TimeInfoHandler(object clock, TimeInfoEventArgs timeInformation);
public event TimeInfoHandler TimeChange;
public void OnTimeChange(object clock, TimeInfoEventArgs timeInformation)
{
if (TimeChange != null)
TimeChange(clock, timeInformation);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace EventDelegate
{
public class Clock
{
private int _hour;
private int _minute;
private int _second;
public delegate void TimeInfoHandler(object clock, TimeInfoEventArgs timeInformation);
public event TimeInfoHandler TimeChange;
public void OnTimeChange(object clock, TimeInfoEventArgs timeInformation)
{
if (TimeChange != null)
TimeChange(clock, timeInformation);
}
public void Run()
{
for (; ; )
{
Thread.Sleep(1000);
System.DateTime dt = System.DateTime.Now;
if (dt.Second != _second)
{
TimeInfoEventArgs timeInformation = new TimeInfoEventArgs(dt.Hour, dt.Minute, dt.Second);
OnTimeChange(this, timeInformation);
}
_second = dt.Second;
_minute = dt.Minute;
_hour = dt.Hour;
}
}
}
public class TimeInfoEventArgs : EventArgs
{
public TimeInfoEventArgs(int hour, int minute, int second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
public readonly int hour;
public readonly int minute;
public readonly int second;
}
public class DisplayClock
{
public void Subscribe(Clock theClock)
{
theClock.TimeChange += new Clock.TimeInfoHandler(TimeHasChanged);
}
public void TimeHasChanged(object theClock, TimeInfoEventArgs ti)
{
Console.WriteLine("Current Time: {0}:{1}:{2}", ti.hour.ToString(), ti.minute.ToString(), ti.second.ToString());
}
}
public class DisplayClock2
{
public void Subscribe(Clock theClock)
{
theClock.TimeChange += new Clock.TimeInfoHandler(TimeHasChanged2);
}
public void TimeHasChanged2(object theClock, TimeInfoEventArgs ti)
{
Console.WriteLine("Current Time - 2: {0}:{1}:{2}", ti.hour.ToString(), ti.minute.ToString(), ti.second.ToString());
}
}
class Program
{
public static void Main()
{
Clock theClock = new Clock();
DisplayClock dc = new DisplayClock();
dc.Subscribe(theClock);
DisplayClock2 dc2 = new DisplayClock2();
dc2.Subscribe(theClock);
theClock.Run();
}
}
}
代码中,Clock类是所谓的“消息”,Subscriber可以将事件注册到event中从而得到消息订阅,简单易用