DEV Community

Gaurav
Gaurav

Posted on • Edited on

4 3

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

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay