Design Pattern: Singleton

Sometimes it is important to have only one instance of a class. Singleton Pattern means that a class is responsible to instantiate itself, so that it can make sure it creates no more than one instance. In the same time, it should provide a global access to that instance.

*Something Important:

1. A static member in the “Singleton” class(Since the getInstance method is static, the instance should be static)

2. A private constructor (so that only the class itself can instantiate an instance)

3. A static public method that returns a reference to the static member

There are two main kinds of implementation of Singleton Pattern.

1. Lazy Instantiation

public class Singleton {
	private static Singleton instance = null;
	private Singleton(){

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

        public void doSomething() {
		System.out.println("doSomething(): Singleton does something!");
	}

}

2. Early Instantiation

//Early instantiation using implementation with static field.
class Singleton {
	private static Singleton instance = new Singleton();

	private Singleton() {
		System.out.println("Singleton(): Initializing Instance");
	}

	public static Singleton getInstance() {
		return instance;
	}

	public void doSomething() {
		System.out.println("doSomething(): Singleton does something!");
	}
}

Protected constructor

It is possible to use a protected constructor to in order to permit the subclassing of the singleton. This techique has 2 drawbacks that makes singleton inheritance impractical:
1.  If the constructor is protected, it means that the class can be instantiated by calling the constructor from another class in the same package. A possible solution to avoid it is to create a separate package for the singleton.
2. In order to use the derived class all the getInstance calls should be changed in the existing code from Singleton.getInstance() to NewSingleton.getInstance().

FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *