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.
What the pattern is trying to do
Ensure a class has only one instance and provide a global access point to it.
What force creates the need
Some services or registries must be centralized, but the system should prevent accidental multiple instances.
How the pattern responds
Hide construction and expose controlled access to a single shared instance.
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 in the Order Management domain
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";
}
}
Step by step
- The constructor is private so callers cannot create extra instances.
- The static instance centralizes access.
- The pattern solves the narrow problem of enforcing a single shared instance.
- In real systems, dependency injection often provides better testability than explicit singletons.
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 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
What this pattern costs
- Easy global access can hide coupling
- Testing and replacement are harder than with explicit dependencies
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.
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.