Files
.circleci
.github
.mvn
abstract-document
abstract-factory
active-object
acyclic-visitor
adapter
aggregator-microservices
ambassador
api-gateway
ar
arrange-act-assert
assets
async-method-invocation
balking
bridge
builder
business-delegate
bytecode
caching
callback
chain
circuit-breaker
cloud-static-content-hosting
collection-pipeline
combinator
command
commander
composite
composite-entity
converter
cqrs
dao
data-bus
data-locality
data-mapper
data-transfer-object
decorator
delegation
dependency-injection
dirty-flag
double-buffer
double-checked-locking
double-dispatch
eip-aggregator
eip-message-channel
eip-publish-subscribe
eip-splitter
eip-wire-tap
etc
event-aggregator
event-asynchronous
event-driven-architecture
event-queue
event-sourcing
execute-around
extension-objects
facade
factory
factory-kit
factory-method
feature-toggle
filterer
fluentinterface
flux
flyweight
fr
front-controller
game-loop
guarded-suspension
half-sync-half-async
hexagonal
intercepting-filter
interpreter
iterator
ko
layers
lazy-loading
leader-election
leader-followers
marker
master-worker-pattern
mediator
memento
model-view-controller
model-view-presenter
model-view-viewmodel
module
monad
monostate
multiton
mute-idiom
naked-objects
null-object
object-mother
object-pool
observer
page-object
parameter-object
partial-response
pipeline
poison-pill
priority-queue
private-class-data
producer-consumer
promise
property
prototype
proxy
queue-load-leveling
reactor
reader-writer-lock
registry
repository
resource-acquisition-is-initialization
retry
role-object
saga
separated-interface
servant
serverless
service-layer
service-locator
sharding
singleton
etc
src
README.md
pom.xml
spatial-partition
special-case
specification
state
step-builder
strangler
strategy
subclass-sandbox
template-method
thread-pool
throttling
tls
tolerant-reader
tr
trampoline
transaction-script
twin
typeobjectpattern
unit-of-work
update-method
value-object
version-number
visitor
zh
.all-contributorsrc
.gitignore
CONTRIBUTING.MD
LICENSE.md
PULL_REQUEST_TEMPLATE.md
README.md
checkstyle-suppressions.xml
license-plugin-header-style.xml
lombok.config
mvnw
mvnw.cmd
pom.xml
java-design-patterns/singleton

layout, title, folder, permalink, categories, tags
layout title folder permalink categories tags
pattern Singleton singleton /patterns/singleton/ Creational
Gang of Four

Intent

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

Explanation

Real world example

There can only be one ivory tower where the wizards study their magic. The same enchanted ivory tower is always used by the wizards. Ivory tower here is singleton.

In plain words

Ensures that only one object of a particular class is ever created.

Wikipedia says

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

Programmatic Example

Joshua Bloch, Effective Java 2nd Edition p.18

A single-element enum type is the best way to implement a singleton

public enum EnumIvoryTower {
  INSTANCE
}

Then in order to use:

var enumIvoryTower1 = EnumIvoryTower.INSTANCE;
var enumIvoryTower2 = EnumIvoryTower.INSTANCE;
assertEquals(enumIvoryTower1, enumIvoryTower2); // true

Class diagram

alt text

Applicability

Use the Singleton pattern when

  • There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point
  • When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code

Typical Use Case

  • The logging class
  • Managing a connection to a database
  • File manager

Real world examples

Consequences

  • Violates Single Responsibility Principle (SRP) by controlling their own creation and lifecycle.
  • Encourages using a global shared instance which prevents an object and resources used by this object from being deallocated.
  • Creates tightly coupled code. The clients of the Singleton become difficult to test.
  • Makes it almost impossible to subclass a Singleton.

Credits