I need help trying to understand the Observer Pattern and Delegates. I found this code on another website and I am trying to understand what it is actually doing. Can someone help me out.
When I execute the code, I get both of the messages "Server is up and running" and "Server is down, We are working on it it will be back soon". I think I am getting both of the message because in the Main, there is a server.ServerStatus = true; and a server.ServerStatus = false. However, if I comment out the server.ServerStatus = true; and run then I I get the message "Server is up and running" but I expected to only see "Server is down, We are working on it it will be back soon.". Can someone explain? Susan
class Program
{
static void Main(string[] args)
{
Server server = new Server();
server.ServerStatusChanged += new EventHandler(ProcessServerStatus);
server.ServerStatus = true;
server.ServerStatus = false;
Console.Read();
}
public class Server
{
public event EventHandler ServerStatusChanged;
private bool _ServerStatus;
public bool ServerStatus
{
get { return this._ServerStatus; }
set {
if (this._ServerStatus == value) return; // Dont need to do anything;
if (this.ServerStatusChanged != null) // make sure the invocation list is not empty
ServerStatusChanged(value, new EventArgs()); // Firing Event
this._ServerStatus = value;
}
}
}
public static void ProcessServerStatus(object sender, EventArgs e)
{
bool status = (bool)sender;
if (status)
Console.WriteLine("Server is up and running");
else
Console.WriteLine("Server is down, We are working on it it will be back soon");
}
}