-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvents.cs
75 lines (63 loc) · 1.78 KB
/
Events.cs
1
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
using System;
using System.Threading;
namespace hello_world {
public class TimeInfoEventArg {
public int Hour {get; set;}
public int Minute {get; set;}
public int Second {get; set;}
public TimeInfoEventArg(int h, int m, int s) {
this.Hour = h;
this.Minute = m;
this.Second = s;
}
}
public class Clock {
private int second = 0;
public delegate void SecondChangeHandler(object Clock, TimeInfoEventArg timeInfo);
public event SecondChangeHandler SecondChanged;
public void Run() {
while(true) {
Thread.Sleep(1000);
DateTime now = DateTime.Now;
if(now.Second != second) {
TimeInfoEventArg timeInfoEventArg =
new TimeInfoEventArg(
now.Hour, now.Minute, now.Second
);
if(SecondChanged != null) {
SecondChanged(this, timeInfoEventArg);
}
}
}
}
}
public class DigitalClock {
public void Subscribe(Clock theClock) {
theClock.SecondChanged += NewTime;
}
public void NewTime(object o, TimeInfoEventArg e) {
Console.WriteLine($"Current Time: {e.Hour.ToString()}:{e.Minute.ToString()}:{e.Second.ToString()}");
}
}
public class Log {
public void Subscribe(Clock theClock) {
theClock.SecondChanged += LogTime;
}
public void LogTime(object o, TimeInfoEventArg e) {
Console.WriteLine($"Logging... {e.Hour.ToString()}:{e.Minute.ToString()}:{e.Second.ToString()}");
}
}
public class EventDemo {
public EventDemo() {
this.Demo();
}
public void Demo() {
Clock myClock = new Clock();
DigitalClock digiClock = new DigitalClock();
digiClock.Subscribe(myClock);
Log log = new Log();
log.Subscribe(myClock);
myClock.Run();
}
}
}