private void ValueHasChanged(Object sender, EventArgs e) { Speedometer speedo = (Speedometer)sender; if (speedo.CurrentSpeed > SPEED_TO_ALERT) { Console.WriteLine("** ALERT ** Driving too fast! (" + speedo.CurrentSpeed + ")"); } else { Console.WriteLine("... nice and steady ... (" + speedo.CurrentSpeed + ")"); } }
static void Main() { // Create a speedometer... Speedometer speedo = new Speedometer(); // Create a monitor... SpeedMonitor monitor = new SpeedMonitor(speedo); // Add automatic gearbox as an observer AutomaticGearbox auto = new AutomaticGearbox(speedo); // Drive at different speeds... speedo.CurrentSpeed = 50; speedo.CurrentSpeed = 70; speedo.CurrentSpeed = 40; speedo.CurrentSpeed = 100; speedo.CurrentSpeed = 69; Console.Read(); }
private void ValueHasChanged(Object sender, EventArgs e) { Speedometer speedo = (Speedometer)sender; if (speedo.CurrentSpeed <= 10) { Console.WriteLine("Now in first gear"); } else if (speedo.CurrentSpeed <= 20) { Console.WriteLine("Now in second gear"); } else if (speedo.CurrentSpeed <= 30) { Console.WriteLine("Now in third gear"); } else { Console.WriteLine("Now in fourth gear"); } }
public AutomaticGearbox(Speedometer speedo) { speedo.ValueChanged += ValueHasChanged; }
public SpeedMonitor(Speedometer speedo) { speedo.ValueChanged += ValueHasChanged; }