FileDocCategorySizeDatePackage
Temperature.javaAPI DocExample2049Tue Jun 03 21:58:06 BST 1997BeansBook.Simulator

Temperature.java

// This example is from the book Developing Java Beans by Robert Englander. 
// Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.

// Chapter 2 -- The Temperature class

package BeansBook.Simulator;

import java.util.Vector;

public class Temperature
{
   // the current temperature in Celsius
   protected double currentTemp = 22.2;

   // the collection of objects listening for temperature changes
   private Vector tempChangeListeners = new Vector();

   // the constructors
   public Temperature(double startingTemp)
   {
      currentTemp = startingTemp;
   }

   public Temperature()
   {
   }

   // add a temperature change listener
   public synchronized void
   addTempChangeListener(TempChangeListener l)
   {
      // add a listener if it is not already registered
      if (!tempChangeListeners.contains(l))
      {
         tempChangeListeners.addElement(l);
      }
   }

   // remove a temperature change listener
   public synchronized void 
   removeTempChangeListener(TempChangeListener l)
   {
      // remove it if it is registered
      if (tempChangeListeners.contains(l))
      {
         tempChangeListeners.removeElement(l);
      }  
   }

   // notify listening objects of temperature changes
   protected void notifyTemperatureChange()
   {
      // create the event object
      TempChangedEvent evt = new TempChangedEvent(this, currentTemp);

      // make a copy of the listener object vector so that it cannot
      // be changed while we are firing events
      Vector v;
      synchronized(this)
      {
         v = (Vector) tempChangeListeners.clone();
      }

      // fire the event to all listeners
      int cnt = v.size();
      for (int i = 0; i < cnt; i++)
      {
         TempChangeListener client = (TempChangeListener)v.elementAt(i);
         client.tempChanged(evt);
      }
   }
}