// 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 5 -- The SimpleTemperature class

import BeansBook.Simulator.*;
import java.io.*;
import java.util.*;

public class SimpleTemperature
{
   // collection of temperature change listeners
   protected transient Vector listeners = null;

   public synchronized void 
   addTemperatureChangeListener(TemperatureChangeListener l)
   {
      // if the vector doesn't exist yet, create it now
      if (listeners == null)
      {
         listeners = new Vector();
      }

      // add the listener
      if (!listeners.contains(l))
      {
         listeners.addElement(l);
      }
   }

   public synchronized void 
   removeTemperatureChangeListener(TemperatureChangeListener l)
   {
      // if we have a collection of listeners, attempt to remove
      // the specified listener
      if (listeners != null)
      {
         listeners.removeElement(l);
      }
   }

   private void writeObject(ObjectOutputStream stream)
               throws java.io.IOException
   {
       // perform default writing first
       stream.defaultWriteObject();

       // clone the vector in case one is added or removed
       Vector v = null;
       synchronized (this) 
       {
          if (listeners != null) 
          {
             v = (Vector)listeners.clone();
          }
       }

       // if we have a collection…
       if (v != null) 
       {
          int cnt = v.size();
          for(int i = 0; i < cnt; i++) 
          {
             // get the listener element from the collection
             TemperatureChangeListener l = 
                      (TemperatureChangeListener)v.elementAt(i);
            
             // if the listener is serializable, write it to the stream
             if (l instanceof Serializable) 
             {
                stream.writeObject(l);
             }
          }
       }
       
       // a null object marks the end of the listeners 
       stream.writeObject(null);
   }

   // handle the reading of the object state
   private void readObject(ObjectInputStream stream)
      throws java.io.IOException
   {
      try
      {
         stream.defaultReadObject();
         
         Object l;
         while(null != (l = stream.readObject())) 
         {
            addTemperatureChangeListener((TemperatureChangeListener)l);
         }
      }
      catch (ClassNotFoundException e)
      {
         throw new IOException();
      }
   }
}

