Singleton Pattern

📢 This article was translated by gemini-2.5-flash

Singleton Pattern: Object Creational Pattern

Intent

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

Structure

image

Here’s the breakdown:

  • Singleton: Defines an Instance operation that lets clients access its unique instance.
  • Instance is a class operation; it might be responsible for creating its own unique instance.

Applicability

Use the Singleton pattern when:

  • A class must have exactly one instance, and clients can access it from a well-known access point.
  • The sole instance should be extensible by subclassing, and clients should be able to use an extended instance without changing their code.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class main{
    // s1 and s2 are the same instance (same memory address)
    Singleton s1 = Singleton.getInstance();
    Singleton s2 = Singleton.getInstance();
}

class Singleton{
    private int num = 2023;

    public void setNum(int num){
        this.num = num;
    }
    public int getNum(){
        return this.num;
    }

    private Singleton(){}

    private static Singleton instance = new Singleton();

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