Java Omnibus
OOAD & Architecture / GoF patterns / Creational / Singleton Pattern in Java
GoF Creational Java Order Management
GoF Pattern

Singleton solves a narrow problem well, but it is one of the easiest GoF patterns to misuse in Java.

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

Intent

What the pattern is trying to do

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

Problem

What force creates the need

Some services or registries must be centralized, but the system should prevent accidental multiple instances.

Solution

How the pattern responds

Hide construction and expose controlled access to a single shared instance.

Structure

How the moving parts fit together

A Singleton owns its constructor and returns one stable instance through a static access path or equivalent controlled mechanism.

Java Example

Java example in the Order Management domain

Singleton Pattern in Java example
package org.javaomnibus.ecommerce.gof.creational;

public final class CurrencyRegistry {
    private static final CurrencyRegistry INSTANCE = new CurrencyRegistry();

    private CurrencyRegistry() {}

    public static CurrencyRegistry instance() {
        return INSTANCE;
    }

    public String defaultCurrency() {
        return "USD";
    }
}
Code Walkthrough

Step by step

  1. The constructor is private so callers cannot create extra instances.
  2. The static instance centralizes access.
  3. The pattern solves the narrow problem of enforcing a single shared instance.
  4. In real systems, dependency injection often provides better testability than explicit singletons.
When To Use

Where this pattern helps

  • For truly shared immutable registries or narrow infrastructure coordination points
  • When one instance is a real invariant rather than a convenience preference
When Not To Use

When a simpler design is better

  • When the object has hidden mutable state that will leak globally
  • When dependency injection or application-scoped lifecycle management already solves the problem better
Trade-Offs

What this pattern costs

  • Easy global access can hide coupling
  • Testing and replacement are harder than with explicit dependencies
Modern Relevance

How this fits today

Modern Java teams use Singleton more cautiously because DI containers, application scopes, and configuration systems often make hard-coded global singletons unnecessary.

Common Misuse

Where teams get it wrong

Using Singleton as a shortcut for service location or shared mutable state is one of the most common abuses of the pattern.

Related Patterns

Compare with nearby choices


What To Read Next