DEV Community

Gaurav
Gaurav

Posted on • Updated on

Decode Singleton Pattern

When to use

  • Application needs “only one instance” of a class.
  • To have complete control over the instance creation.

Intent

Ensure a class has only one instance, and provide a global point of access to it.


Components

  • Singleton Class

Structure

Singleton


Implementation

Create a Singleton class with a static instance and a private constructor. Provide a static method to allow access to this 'only' instance.

1 Create a Singleton Class

package com.gaurav.singleton;

public class Singleton {

  /* the singleton obj */
  private static Singleton instance = null;

  /* private constructor to avoid
     external instantiation of this class */
  private Singleton() {
  }

  /* method to get the singleton obj */
  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class) {
        /* double checked locking */
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance;
  }

  public void printObj() {
    System.out.println("Unique Id of the obj: "
    + System.identityHashCode(this));
  }

}
Enter fullscreen mode Exit fullscreen mode

2 Access the singleton instance

class Demo {

  public static void main(String[] args) {
    Singleton obj1 = Singleton.getInstance();
    obj1.printObj();
    Singleton obj2 = Singleton.getInstance();
    obj2.printObj();
  }

}
Enter fullscreen mode Exit fullscreen mode

Output

Unique Id of the obj: 1916222108
Unique Id of the obj: 1916222108
Enter fullscreen mode Exit fullscreen mode

Benefits

  • Controlled instantiation
  • Supports both EAGER and LAZY initializations
  • Singletons can be converted to Multitons (to support limited number of instances identified by keys)

Drawbacks

  • Singleton is often seen as 'not-so-good' design as it resembles global variables
  • Special handling is required if the Singleton object needs to be deleted
  • Singletons that maintain global state may cause issues

Real World Examples

  • The Office of the President (there can be only one President at any given time)

Software Examples

  • Logger classes
  • Window Manager
  • Printer Spooler

Java SDK Examples

java.lang.Runtime.getRuntime( )
java.awt.Toolkit.getDefaultToolkit( )
java.awt.Desktop.getDesktop( )
java.util.logging.LogManager.getLogManager( )
java.lang.System#getSecurityManager( )


Want to discuss more
Lets have a Coffee

Discussion (1)