Monday, December 15, 2014

Singleton Pattern

Problem:

What if you want only one Object of a class? What if there is a need to have only one Object?

Solution:

The answer is "use Singleton design pattern".

So what does Singleton design pattern suggests:
  • Ensure that a class has only one instance
  • Provide a global access point to it

Implementation:
  1. Create a class
  2. Create a constructor and mark it private [so that no one else can create an instance of this class]
  3. Create a private static member variable in this class [and initialize it with null value]
  4. Create a new static method which provides way to create an instance of this class, first thing to do in this method is to make sure that there is no instance of this class created already, if not, create a new instance, store its reference in a member variable and return a reference to this instance otherwise return a previously created reference.

Java Code:

// Lazy instantiation example (called classic singleton)
public class TheSingleton {

    private static TheSingleton singleton = null;

    // restrict the instantiation by using private constructor
    private TheSingleton() {}

    // way to create an instance (only way)
    public static TheSingleton getInstance() {
        if ( singleton == null ) {
            singleton = new TheSingleton();
        }
        return singleton;
    }

    public doSomething() {
         // ....
    }

}

Above implementation is not thread-safe.

Here is thread-safe implementation using "eager instantiation" approach. Instance is created by JVM as soon as the class is loaded.

// Eager instantiation example (thread-safe)
public class TheSingleton {

    private static TheSingleton singleton = new TheSingleton();

    // restrict the instantiation by using private constructor
    private TheSingleton() {}

    // global access point
    public static TheSingleton getInstance() {
        return singleton;
    }

    public doSomething() {
         // ....
    }

}

Note: Another approach to make a Lazy singleton implementation thread-safe is to declare a getInstance method with synchronized keyword. But there is a downside to it, that is synchronization is expensive (because every call to the method is synchronized)!

Applications of Singleton Design Pattern:

  • Logging 
  • Connection pools
  • Thread pools
  • Registry object
  • Printer object
  • Device object
  • UI dialog

No comments:

Post a Comment