creational
Singleton
Ensure a class has only one instance and provide a global access point to it.
Some resources are meant to exist exactly once for the lifetime of a program — the application configuration, a logger, a thread pool, or a database connection pool. If several copies are created independently, they drift out of sync, fight over the same underlying handle, or quietly waste memory. The Singleton pattern guarantees a class has a single shared instance and gives the rest of the codebase one well-known way to reach it.
A country has one government — no matter who asks, they get the same governing body.
Key Concepts
1
Mechanically, the constructor is made private so no caller can run new directly. A static accessor (commonly getInstance()) creates the instance on first use and returns that same cached object on every subsequent call. The first-call check is the subtle part: in a multithreaded program two threads can race into the constructor at once. The idiomatic fixes in Java are an enum singleton, an eagerly-initialised static final field, the initialization-on-demand holder idiom, or a volatile field guarded by double-checked locking.
newgetInstance()enumstatic finalvolatile
2
Reach for it when you genuinely have one shared source of truth: configuration, a logger or audit trail, a connection pool, or a cache. The catch is that a Singleton is global mutable state by another name. It makes unit tests awkward because the shared instance leaks between tests, it hides dependencies that a constructor parameter would have made explicit, and it can become a bottleneck if every thread funnels through it. Many teams now express "one instance" through a dependency-injection container — the container owns a single instance, but classes still receive it as an ordinary constructor argument, keeping them testable.