- Published on
Singleton Design Pattern
- Authors
- Name
- Iraianbu A
Table of Contents
- Introduction
- Problem
- Real World Examples
- Structure
- Implementation in Java
- Advantages
- Disadvantages
- Relationship with other patterns
- References
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:
- Ensure that a class has only one instance. (Database connection, Logger, File system)
- Provide a global access point to that instance. (Global state)
Real World Examples
- Passport
- Government
- Logger
- Database connection pool
- 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
andjava.awt.Desktop
Structure

Source: Refactoring Guru
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
- Singleton can be used to implement other patterns like Abstract Factory, Builder, and Prototype.
- A Facade pattern can often be implemented as a Singleton when only one access point is needed.
- 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)