Published on

Singleton Design Pattern

Authors
  • avatar
    Name
    Iraianbu A
    Twitter

Table of Contents

Introduction

Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.

Problem

The Singleton pattern solves two problems at the same time, violating the Single Responsibility Principle:

  1. Ensure that a class has only one instance. (Database connection, Logger, File system)
  2. Provide a global access point to that instance. (Global state)

Real World Examples

  1. Passport
  2. Government
  3. Logger
  4. Database connection pool
  5. Caching Mechanism
  • It is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade, etc.

  • It is used in core Java classes like java.lang.Runtime and java.awt.Desktop

Structure

Implementation in Java

Eager Initialization

import java.io.Serializable;

/**
 * If the singleton class not using a lot of resource, we can go
 * for Eager Singleton. There is no options for exception
 * handling. Good for single threaded environment.
 */
public class EagerSingleton implements Cloneable,Serializable {
    private static final EagerSingleton instance = new EagerSingleton();

    private EagerSingleton() {
        /**
         * This is to prevent the class from being instantiated
         * using reflection.
         */
        if(instance != null){
            throw new RuntimeException("Use getInstance() method to get the instance");
        }

    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        /*
         * This is to prevent the class from being cloned
         * using the clone() method.
         */
        if(instance != null){
            throw new CloneNotSupportedException("Use getInstance() method to get the instance");
        }
        return super.clone();
    }

    /**
     * This is to prevent the class from being deserialized
     * using the readObject() method.
     */
    private Object readResolve() {
        return instance;
    }

    public static EagerSingleton getInstance(){
        return instance;
    }
}

Static Block Initialization

Lazy Initialization

Thread Safe Singleton

Double Checked Locking

Bill Pugh Singleton

Enum Singleton

Advantages

  • Be sure that a class has only a single instance.
  • Control the global access to the instance.
  • The singleton object is created only when it is needed.

Disadvantages

  • Violates the Single Responsibility Principle.
  • Requires special handling in multithreaded environments.

Relationship with other patterns

  1. Singleton can be used to implement other patterns like Abstract Factory, Builder, and Prototype.
  2. A Facade pattern can often be implemented as a Singleton when only one access point is needed.
  3. Singleton vs Flyweight:
    • Singleton: Only one instance exists for the entire application
    • Flyweight: Multiple instances exist, each with different internal states
    • Singleton objects can be changed (mutable), while Flyweight objects cannot be changed (immutable)

References