2012年9月27日木曜日

開発環境

『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第17章(デリゲートとイベント)16.12(練習問題)練習7-4を解いてみる。

その他参考書籍

練習17-4.

コード

using System;
using System.Threading;

class TimeInfoEventArgs : EventArgs
{
    public readonly string message;
    public TimeInfoEventArgs(string message)
    {
        this.message = message;
    }
}

class Clock
{
    private DateTime start;
    private DateTime stop;
    private string message;
    public Clock(int hour, int minute, int second, string message)
    {
        this.start = DateTime.Now;
        TimeSpan duration = new TimeSpan(hour, minute, second);
        this.stop = this.start + duration;
        this.message = message;
    }
    public delegate void SecondChangeHandler
        (object clock, TimeInfoEventArgs timeInformation);
    public event SecondChangeHandler SecondChanged;
    public void Run()
    {
        for (; ; )
        {
            Thread.Sleep(1000);
            DateTime dt = DateTime.Now;
            if (dt >= stop)
            {
                TimeInfoEventArgs timeInformation =
                    new TimeInfoEventArgs(this.message);
                if (SecondChanged != null)
                {
                    SecondChanged(this, timeInformation);
                    break;
                }
            }
        }
    }
}
class DisplayClock
{
    public void Subscribe(Clock theClock)
    {
        theClock.SecondChanged +=
            new Clock.SecondChangeHandler(TimeHasChanged);
    }
    public void TimeHasChanged(object theClock, TimeInfoEventArgs ti)
    {
        Console.WriteLine("DisplayClock: {0}", ti.message);
    }
}
class Log
{
    public void Subscribe(Clock theClock)
    {
        theClock.SecondChanged +=
            new Clock.SecondChangeHandler(Expired);
    }
    public void Expired(object theClock, TimeInfoEventArgs ti)
    {
        Console.WriteLine("Log: {0}", ti.message);
    }
}

class Tester
{
    public void Run()
    {
        Console.WriteLine("通知してほしい経過時間を入力(時間、分、秒)");
        int hour = Convert.ToInt16(Console.ReadLine());
        int minute = Convert.ToInt16(Console.ReadLine());
        int second = Convert.ToInt16(Console.ReadLine());
        Console.Write("経過時に表示するメッセージを入力: ");
        string message = Console.ReadLine();
        Clock clock = new Clock(hour, minute, second, message);
        DisplayClock dc = new DisplayClock();
        dc.Subscribe(clock);
        Log log = new Log();
        log.Subscribe(clock);
        clock.Run();
    }
    static void Main()
    {
        Tester t = new Tester();
        t.Run();
    }
}

入出力結果(Console Window)

通知してほしい経過時間を入力(時間、分、秒)
0
0
10
経過時に表示するメッセージを入力: ロケット発射
DisplayClock: ロケット発射
Log: ロケット発射
続行するには何かキーを押してください . . .

0 コメント:

コメントを投稿