This is a class which holds the information about the
event.
public class TimeEventArgs
: EventArgs
{
public
TimeEventArgs(string currentTime)
{
this.CurrentTime
= currentTime;
}
public string CurrentTime;
}
This is a Subject class (Publisher) that the other classes
will observe. So it publishes a handler so that other observer classes can subscribe
to it.
public class Clock
{
public delegate void SecondChangeHandler(object
clock, TimeEventArgs e);
public SecondChangeHandler OnSecondChange;
public void RunClock()
{
for
(int i = 0; i <= 4; i++)
{
Thread.Sleep(1000);
TimeEventArgs
te = new TimeEventArgs(DateTime.Now.ToString("HH:mm:ss"));
if
(OnSecondChange != null)
{
OnSecondChange(this, te);
}
}
}
}
This
is a Fisrt Observer class which is subscribed to Clock class
public class DisplayClock
{
public void Subscribe(Clock
clock)
{
clock.OnSecondChange += new Clock.SecondChangeHandler(TimeChanged);
}
private
void TimeChanged(object
clock, TimeEventArgs te)
{
Console.WriteLine("Time Changed :: " + te.CurrentTime);
}
}
This
is a Second Observer class which is subscribed to Clock class
public class LogClock
{
public void Subscribe(Clock
clock)
{
clock.OnSecondChange += new Clock.SecondChangeHandler(LogTimeChanged);
}
private
void LogTimeChanged(object
clock, TimeEventArgs te)
{
Console.WriteLine("Log Time : " + te.CurrentTime);
}
}
Now test the Publish Subscribe
static void Main(string[]
args)
{
Clock
clock = new Clock();
DisplayClock
dc = new DisplayClock();
dc.Subscribe(clock);
LogClock
lc = new LogClock();
lc.Subscribe(clock);
clock.RunClock();
Console.ReadLine();
}
Comments
Post a Comment