The Singleton Pattern

The singleton design pattern is used when only one instance of an object is needed throughout the lifetime of an application. The singleton class is instantiated at the time of first access and the same instance is used thereafter till the application quits. To ensure that the user can create only one instance of this class, the following things have to be taken care of.

  1. Make sure the user cannot explicitly create an instance of this object.
  2. Provide access to this object from all areas of the application so that the need to create another instance never arises.

Uses :
The Singleton class can be used in various places where one would need a common repository of information that can be accessed from all objects in an application. A common example could be Preferences for the user. The preferences can be loaded from a file into memory into a singleton class which all objects in the application can then access to get preferences information.

Code

/*
 * This example is from javareference.com
 * for more information visit,
 * http://www.javareference.com
 */

//package 
package com.jref.examples.singleton;

//import statements 
import java.util.*;

/**
 * Singleton.java 
 *
 * Class demonstrating singleton pattern in java 
 *
 * @author Anand Hariharan([email protected]) 
 */
public class Singleton
{
    // Needs to be static as the instance has to be created from 
    // the static function getInstance(). 
    private static Singleton m_SingletonInstance = null;

    // For illustration only 
    private Hashtable m_PrefsHash = null;

    /**
     * Create a private constructor so that the singleton class 
     * cannot be instantiated by the developer explicitly. 
     */
    private Singleton()
    {
        // Do initialization. 
        // In case of Preferences, load preferences from the Prefs file. 

        // For sake of illustration, the hastable has 
        // preferences for each user. 

        m_PrefsHash = new Hashtable();
        m_PrefsHash.put("a","Prefs for A");
        m_PrefsHash.put("b","Prefs for B");
        m_PrefsHash.put("c","Prefs for C");
        m_PrefsHash.put("d","Prefs for D");
        m_PrefsHash.put("e","Prefs for E");
        m_PrefsHash.put("f","Prefs for F");
    }

    /**
     * Function to get the singleton instance. It is public static 
     * so that any object can call this function without an instance 
     * of "Singleton" and get access to the one and only instance of
     * this class. 
     */
    public static Singleton getInstance()
    {
        if(m_SingletonInstance == null)
            m_SingletonInstance = new Singleton();

        return m_SingletonInstance;
    }
    /**
     * Dummy function to illustrate the singleton class. 
     * The string in the hashtable can be replaced with a 
     * custom preferences object. 
     */
    public String getPrefsFor(String username)
    {
        return (String)m_PrefsHash.get(username);
    }

}
// END OF Singleton.java 

/*
 * This example is from javareference.com
 * for more information visit,
 * http://www.javareference.com
 */

//package
package com.jref.examples.singleton;

/**
 * SingletonExample.java
 *
 * Class demonstrating singleton pattern in java
 *
 * @author Anand Hariharan([email protected])
 */
public class SingletonExample
{
    public static void main(String[] args)
    {
        System.out.println(Singleton.getInstance().getPrefsFor("a"));
        System.out.println(Singleton.getInstance().getPrefsFor("f"));
    }
}

Leave a Reply