出版社:
システムの使用;
System.Collections.Generic;を使用します。
System.Linqを使用します。
System.Textを使用します。
System.Threadingを使用します。
System.Threading.Tasksを使用します。
namespace clock
{
class Clock // publicで継承可能に、publisherクラス
{
private int
_hour;
private int _second;
public int _second; public delegate void SecondChangeHandler(object clock、TimeInfoEventArgs timeInformation、int outdata); //カスタマイズ可能主剤
public event SecondChangeHandler SecondChange; //イベントを定義すると、イベントはデリゲートをカプセル化し、イベントタイプのデリゲートになります。ほとんどの既存の定義
protected void OnSecondChange(object clock、TimeInfoEventArgs timeInformation){//
(SecondChange!= null)の場合にトリガーイベントを定義します{//イベントがサブスクライブされています
SecondChange(clock、timeInformation、1); //イベントによる実行デリゲートメソッド
}
}
public void Run(){//
(;;)の特定の条件下でイベントをトリガーします{
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時間、int分、int秒)
{
this.hour =時間;
this.minute =分;
this.second =秒;
}
}
}
サブスクライバー(オブザーバーモード):
システムの使用;
System.Collections.Generic;を使用します。
System.Linqを使用します。
System.Textを使用します。
System.Threading.Tasksを使用します。
namespace clock
{
class DisplayClock // Observer class(subscriber)
{
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( "現在の時間:{0}:{1}:{2}"、timeInformation.hour.ToString()、
timeInformation.minute.ToString()、
timeInformation.second.ToString());
}
}
クラスLogClock {
public void Subscribe(Clock theClock)
{
theClock.SecondChange + = new Clock.SecondChangeHandler(WriteLogentry);
theClock.SecondChange + =新しい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());
// new NotImplementedException();をスローします
}
private void WriteLogentry(object clock、TimeInfoEventArgs timeInformation、int outdata)
{
//スローする新しいNotImplementedException();
Console.WriteLine( "ファイルへのロギング:{0}:{1}:{2}"、timeInformation.hour.ToString()、
timeInformation.minute.ToString()、
timeInformation.second.ToString());
}
}
}