JMU
The Singleton Pattern
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Requirements of a Singleton
One Implementation of the Singleton Pattern

images/singleton.gif

An Example
A FileViewer
javaexamples/singleton/v1/FileViewer.java (Fragment: skeleton)

/**
 * A Frame that is used to view the contents of a file
 *
 * This class  uses the Singleton pattern 
 * to ensure that there is only one
 * instance at any point in time.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 *
 */
public class FileViewer
{

    private static boolean      exists = false;
    private static FileViewer   instance;

    /**
     * Construct a new FileViewer
     *
     * Note: This method is private and used only internally
     */
    private FileViewer()
    {


        exists = true;
    }

}

        
An Example (cont.)
A FileViewer
javaexamples/singleton/v1/FileViewer.java (Fragment: createInstance)
    /**
     * Construct a new FileViewer (if one doesn't exist)
     * or return the existing instance
     */
    public static FileViewer createInstance()
    {
       if (!exists) instance = new FileViewer(); // exists will become true
       
       return instance;

    }
        
An Example (cont.)
Using a FileViewer
javaexamples/singleton/v1/FileChooser.java (Fragment: valueChanged)
    /**
     * Handle valueChanged events 
     * (required by ListSelectionListener)
     *
     * @param lse   The ListSelectionEvent to handle
     */
    public void valueChanged(ListSelectionEvent lse)
    {
        FileViewer   fv;
        String       fn;

        fn = (String)list.getSelectedValue();

        fv = FileViewer.createInstance();
        fv.load(fn);
    }
        
Thread Safety
An Example (cont.)
Using Eager Instantiation
javaexamples/singleton/v2/FileViewer.java (Fragment: eagerInstantiation)
    private static FileViewer   instance = new FileViewer();
        


javaexamples/singleton/v2/FileViewer.java (Fragment: createInstance)
    /**
     * Return the singleton instance
     */
    public static FileViewer createInstance()
    {
        return instance;
    }