Design Pattern: Singleton

Design Pattern: Singleton

in

The used examples and notions almost come from OOD Design.

Singleton

code example

/*
Because keyword synchronized is very expensive when talking about the performance, we could make a waste after the instance is instantiated. 
*/
class Singleton {
    private static Singleton instance;
    private Singleton() {

    }
    public static synchronized Singleton getInstance() {
        if (instance == null) instance = new Singleton();
        return instance;
    }
}

//Lazy instantiation using double locking mechanism
class Singleton {
    private static Singleton instance;
    private Singleton() {

    }
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized(Singleton.class) {
                if (instance == null) {
                    instance = new Singleton()
                }
            }
        }
        return instance;
    }
}

//Early instantiation using implementation with static field. The class is loaded once so it can guarantee the uniquity of the object
class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton(){}
    public static Singleton getInstance() {
        return instance;
    }
}

/*
Serialization
if a Singeton class implements the java.io.Serializable interface, when the singeton is serialized and then deserialized more than once, there will be multiple instances of the Singleton class created. In order to prevent this the readResolve method should be implemented.
*/
public class Singleton implements Serializable {
    /*
    This method is called immediately after an object of this class is deserialized.
    */
    protected Object readResolve() {
        return get Instance();
    }
}

Intent

  • to make sure only one instance of a class is created
  • provide a global point of access to the object

Applicability

  • Logger
  • Configuration
  • Accessing resources in shared mode
  • Factories implemented as Singletons Combinning Abstract Factory or Factory Method and Singleton design patterns is a common practice. Why ? A factory gives you a separate spot to decide what instances/instance you’re going to get. For example, when you want a wrapper that implements SQL logging, you can pass a subclass.