コード例 #1
0
        public static void Main()
        {
            // Create a Thermostat instance.
            Thermostat t = new Thermostat();

            // Create the Thermostat observers.
            new TemperatureChangeObserver(t);
            new TemperatureAverageObserver(t);

            // Loop, getting temperature readings from the user.
            // Any noninteger value will terminate the loop.
            do
            {
                Console.WriteLine(Environment.NewLine);
                Console.Write("Enter current temperature: ");

                try
                {
                    // Convert the user's input to an integer and use it to set
                    // the current temperature of the Thermostat.
                    t.Temperature = Int32.Parse(Console.ReadLine());
                }
                catch (Exception)
                {
                    // Use the exception condition to trigger termination.
                    Console.WriteLine("Terminating Observer Pattern Example.");

                    // Wait to continue.
                    Console.WriteLine(Environment.NewLine);
                    Console.WriteLine("Main method complete. Press Enter");
                    Console.ReadLine();
                    return;
                }
            } while (true);
        }
コード例 #2
0
 // A constructor that takes a reference to the Thermostat object that
 // the TemperatureAverageObserver object should observe.
 public TemperatureAverageObserver(Thermostat t)
 {
     // Create a new TemperatureChangedEventHandler delegate instance and
     // register it with the specified Thermostat.
     t.TemperatureChanged += this.TemperatureChange;
 }