发布者:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace clock
{
class Clock//public使其可被继承,发布者类
{
private int _hour;
private int _minute;
private int _second;
public delegate void SecondChangeHandler(object clock,TimeInfoEventArgs timeInformation,int outdata);//可自定义的委托代理
public event SecondChangeHandler SecondChange;//定义事件,事件封装委托,成为事件类型的委托。多数类已有的定义
protected void OnSecondChange(object clock, TimeInfoEventArgs timeInformation) {//定义触发事件
if (SecondChange != null) {//事件已被订阅
SecondChange(clock,timeInformation,1);//通过事件执行委托方法
}
}
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);
OnSecondChange(this,timeInformation);
}
_second = dt.Second;
_minute = dt.Minute;
_hour = dt.Hour;
}
}
}
public class TimeInfoEventArgs
{
public readonly int hour;
public readonly int minute;
public readonly int second;
public TimeInfoEventArgs(int hour, int minute, int second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
}
}
订阅者(观察者模式):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace clock
{
class DisplayClock//观察者类(订阅者)
{
public void Subscribe(Clock theClock) {
theClock.SecondChange += new Clock.SecondChangeHandler(TimeHasChange);//通过委托代理将自定义方法注册到类的事件,订阅事件,即先将方法关联到委托,再将委托注册到事件
}
private void TimeHasChange(object clock, TimeInfoEventArgs timeInformation,int outdata)//订阅事件后自生成事件处理函数来响应事件
{
//throw new NotImplementedException();
Console.WriteLine("current time:{0}:{1}:{2}", timeInformation.hour.ToString(),
timeInformation.minute.ToString(),
timeInformation.second.ToString());
}
}
class LogClock {
public void Subscribe(Clock theClock)
{
theClock.SecondChange += new Clock.SecondChangeHandler(WriteLogentry);
theClock.SecondChange += new Clock.SecondChangeHandler(showclocl);
}
private void showclocl(object clock, TimeInfoEventArgs timeInformation, int outdata)
{
Console.WriteLine("show time:{0}:{1}:{2}", timeInformation.hour.ToString(),
timeInformation.minute.ToString(),
timeInformation.second.ToString());
//throw new NotImplementedException();
}
private void WriteLogentry(object clock, TimeInfoEventArgs timeInformation,int outdata)
{
//throw new NotImplementedException();
Console.WriteLine("Logging to file:{0}:{1}:{2}",timeInformation.hour.ToString(),
timeInformation.minute.ToString(),
timeInformation.second.ToString());
}
}
}