1
class TimeInfoEventArgs:EventArgs
2
{
3
public readonly int hour;
4
public readonly int minute;
5
public readonly int second;
6
public TimeInfoEventArgs(int hour,int minute,int second)
7
{
8
this.hour = hour;
9
this.minute = minute;
10
this.second = second;
11
12
}
13
}
14
15
class Clock
16
{
17
private int hour;
18
private int minute;
19
private int second;
20
21
public delegate void SecondChangedHandler(object clock,TimeInfoEventArgs timeInfomation);
22
23
public event SecondChangedHandler OnSecondChange;
24
25
public void Run()
26
{
27
for (; ; )
28
{
29
Thread.Sleep(10);
30
System.DateTime dt = System.DateTime.Now;
31
if(dt.Second!=second)
32
{
33
TimeInfoEventArgs timeInformation = new TimeInfoEventArgs(dt.Hour, dt.Minute, dt.Second);
34
35
if(OnSecondChange!=null)
36
{
37
OnSecondChange(this, timeInformation);
38
}
39
}
40
this.second = dt.Second;
41
this.minute = dt.Minute;
42
this.hour = dt.Hour;
43
}
44
}
45
}
46
class DisplayClock
47
{
48
public void Subscribe(Clock theClock)
49
{
50
theClock.OnSecondChange+=new Clock.SecondChangedHandler(TimeHasChanged);
51
52
}
53
public void TimeHasChanged(object theClock,TimeInfoEventArgs ti)
54
{
55
Console.WriteLine("Current Time:{0}:{1}:{2} ",ti.hour.ToString(),ti.minute.ToString(),ti.second.ToString());
56
}
57
}
58
class LogCurrentTime
59
{
60
public void subscribe(Clock theClock)
61
{
62
theClock.OnSecondChange+=new Clock.SecondChangedHandler(WriteLogEntry);
63
}
64
public void WriteLogEntry(object theClock,TimeInfoEventArgs ti)
65
{
66
Console.WriteLine("Logging to file: {0}:{1}:{2}\n",ti.hour.ToString(),ti.minute.ToString(),ti.second.ToString());
67
68
}
69
70
}
71
class Program
72
{
73
static void Main(string[] args)
74
{
75
Clock theClock = new Clock();
76
DisplayClock dc = new DisplayClock();
77
dc.Subscribe(theClock);
78
LogCurrentTime lct = new LogCurrentTime();
79
lct.subscribe(theClock);
80
theClock.Run();
81
}
82
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82
