Thursday, July 19, 2007

What is Singleton Design Pattern?

The Singleton Design Pattern is a Creational type of design pattern which assures to have only a single instance of a class, as it is necessary sometimes to have just a single instance.The examples can be print spooler,database connection or window manager where you may require only a single object.

In a Singleton design pattern,there is a public, static method which provides an access to single possible instance of the class.The constructor can either be private or protected.
public class SingletonClass {
private static SingletonClass instance = null;
protected SingletonClass() {
// can not be instantiated.
}
public static SingletonClass getInstance() {
if(instance == null) {
instance = new SingletonClass();
}
return instance;
}
}

In the code above the class instance is created through lazy initialization,unless getInstance() method is called,there is no instance created.This is to ensure that instance is created when needed.

public class SingletonInstantiator {
public SingletonInstantiator() {
SingletonClass instance = SingletonClass.getInstance();
SingletonClass anotherInstance =
new SingletonClass();
...
}
}

In snippet above anotherInstance is created which is a perfectly legal statement as both the classes exist in the same package in this case 'default', as it is not required by an instantiator class to extend SingletonClass to access the protected constructor within the same package.So to avoid even such scenario, the constructor could be made private.

4 comments :

Anonymous said...

This is good
But i want some information which situation we can use singleton in cloning

Aniket Sawant on March 1, 2009 at 10:00 PM said...

The above code was the common implementation but there will be different implementation in case of cloning and multi-threaded environment. Refer to following link: https://javadevelopershelp.blogspot.com/2009/02/singleton-pattern-in-java.html

Deepun on March 3, 2009 at 6:42 PM said...

Aniket:
Thanks for sharing the information.

Anonymous said...

The constructor for the singleton class should not be protected but private.

 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2016. Reads: best tracker