Saturday, May 19, 2012

Singleton Design Pattern

Toady Mr. duffer go to his Guru named Goni to learn singleton design pattern.Let stay with Mr. duffer.

Singleton is one of the basic design patten. Name of these pattern comes from mathematical concept of singleton. In mathematics singleton is a set with exactly only one element . Example : Let S = {0} is a set with only one element . So set S is a singleton in mathematics . Hear is the end of background.

Now, i will describe singleton design pattern from software engineering view. Singleton design pattern is a conceptualization or a design pattern to restrict instantiation of a class only one object. And a global access point of that single instance across the system.

Further more :
GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127].

     Example of singleton design pattern :
public class Singleton {
    private static Singleton singleInstance;

    private Singleton() {
    public static Singleton getSingleInstance() {
        if (singleInstance.equals(null)) {
            synchronized (Singleton.class) {
                if (singleInstance.equals(null)) {
                    singleInstance = new Singleton();
        return singleInstance;


    public String helloSingleTon() {
        return "Hello Singles";

When to use :
To coordinate actions across any software system with exactly one instance of a class. One can choose singleton design pattern to achieve these.
Some other use :
The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.
  • Facade Objects are often Singletons because only one Facade object is required.
  • State objects are often Singletons.
Some points need to keep in mind in case of singleton design pattern :
  • It makes unit testing harder .
  • Access to the singleton in a multi-threaded context must be serialised 
  • Advocates of dependency injection would regard this as an anti-pattern, mainly due to its use of private and static methods
  • Sometimes singleton is actually is not a singleton.These issue can be explore with the article When a singleton is not a singleton?
Singleton Design Pattern n JAVA API

java.lang.Runtime#getRuntime()  java.awt.Desktop#getDesktop()

That's all. Thanks for stay with me through the journey of singleton .
Happy Coding.

No comments:

Post a Comment