尔冬橙

博客园 首页 新随笔 联系 订阅 管理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args)
        {
           //创建Clock
            Clock theClock = new Clock();
            //创建显示对象
            DisplayClock dc = new DisplayClock();
            //订阅事件
            dc.Subscribe(theClock);
            //Clock开始运行
            theClock.Run();
        }
    }
    //存放事件信息的类
    public class TimeInfoEventArgs : EventArgs
    {
        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;
        }
    }
    //Clock:事件发布者
    public class Clock
    {
        private int hour;
        private int minute;
        private int second;
        //委托,事件订阅者实现
        public delegate void SecondChangeHandler(object clock, TimeInfoEventArgs timeInformation);
        //事件,委托类型的事件
        public event SecondChangeHandler onSecondChange;
        public void Run()
        {
            for (; ; )
            {
                Thread.Sleep(1000);
                DateTime dt = DateTime.Now;
                //如果秒钟改变,通知订阅者
                if (dt.Second != second)
                {
                    //创建事件信息对象,传给事件订阅者
                    TimeInfoEventArgs timeInformation = new TimeInfoEventArgs(dt.Hour,dt.Minute,dt.Second);
                    //如果有人订阅,通知他
                    if (onSecondChange != null)
                    {
                        onSecondChange(this, timeInformation);
                    }
                }//更新时间
                this.hour = dt.Hour;
                this.minute = dt.Minute;
                this.second = dt.Second;
            }
        }
    }
    //事件的订阅者
    public class DisplayClock
    {
        //订阅Clock的OnSecondChange事件
        public void Subscribe(Clock theClock)
        { 
            //把方法委托给事件,当被通知(事件发生)时,被委托的方法会执行
            theClock.onSecondChange += new Clock.SecondChangeHandler(TimeHasChanged);

        }
        //被委托的方法
        public void TimeHasChanged(object theClock,TimeInfoEventArgs ti)
        {
            Console.WriteLine("Current time:{0}:{1}:{2}",ti.hour,ti.minute,ti.second);
        }
    }
}

 

posted on 2012-07-22 17:20  尔冬橙  阅读(178)  评论(0)    收藏  举报