mirror of
https://github.com/tiennm99/java-design-patterns.git
synced 2026-05-14 10:58:42 +00:00
6cd2d0353a
* update yaml frontmatter format * update abstract document * update abstract factory * use the new pattern template * acyclic visitor seo * adapter seo * ambassador seo * acl seo * aaa seo * async method invocation seo * balking seo * bridge seo * builder seo * business delegate and bytecode seo * caching seo * callback seo * chain seo * update headings * circuit breaker seo * client session + collecting parameter seo * collection pipeline seo * combinator SEO * command seo * cqrs seo * commander seo * component seo * composite seo * composite entity seo * composite view seo * context object seo * converter seo * crtp seo * currying seo * dao seo * data bus seo * data locality seo * data mapper seo * dto seo * decorator seo * delegation seo * di seo * dirty flag seo * domain model seo * double buffer seo * double checked locking seo * double dispatch seo * dynamic proxy seo * event aggregator seo * event-based asynchronous seo * eda seo * event queue seo * event sourcing seo * execute around seo * extension objects seo * facade seo * factory seo * factory kit seo * factory method seo * fanout/fanin seo * feature toggle seo * filterer seo * fluent interface seo * flux seo * flyweight seo * front controller seo * function composition seo * game loop seo * gateway seo * guarded suspension seo * half-sync/half-async seo * health check seo * hexagonal seo * identity map seo * intercepting filter seo * interpreter seo * iterator seo * layers seo * lazy loading seo * leader election seo * leader/followers seo * lockable object seo * rename and add seo for marker interface * master-worker seo * mediator seo * memento seo * metadata mapping seo * microservice aggregator seo * api gw seo * microservices log aggregration seo * mvc seo * mvi seo * mvp seo * mvvm seo * monad seo * monitor seo * monostate seo * multiton seo * mute idiom seo * naked objects & notification seo * null object seo * object mother seo * object pool seo * observer seo * optimistic locking seo * page controller seo * page object seo * parameter object seo * partial response seo * pipeline seo * poison pill seo * presentation model seo * private class data seo * producer-consumer seo * promise seo * property seo * prototype seo * proxy seo * queue-based load leveling seo * reactor seo * registry seo * repository seo * RAII seo * retry seo * role object seo * saga seo * separated interface seo * serialized entity seo * serialized lob seo * servant seo * server session seo * service layer seo * service locator seo * service to worker seo * sharding seo * single table inheritance seo * singleton seo * spatial partition seo * special case seo * specification seo * state seo * step builder seo * strangler seo * strategy seo * subclass sandbox seo * table module seo * template method seo * throttling seo * tolerant reader seo * trampoline seo * transaction script seo * twin seo * type object seo * unit of work seo * update method seo * value object seo * version number seo * virtual proxy seo * visitor seo * seo enhancements * seo improvements * SEO enhancements * SEO improvements * SEO additions * SEO improvements * more SEO improvements * rename hexagonal + SEO improvements * SEO improvements * more SEO stuff * SEO improvements * SEO optimizations * SEO enhancements * enchance SEO * improve SEO * SEO improvements * update headers
110 lines
4.5 KiB
Markdown
110 lines
4.5 KiB
Markdown
---
|
|
title: "Singleton Pattern in Java: Implementing Global Access Points in Java Applications"
|
|
shortTitle: Singleton
|
|
description: "Explore the Singleton Pattern in Java with our comprehensive guide. Learn how to implement efficient object management for your Java applications, ensuring optimal use of resources and easy access with examples and detailed explanations."
|
|
category: Creational
|
|
language: en
|
|
tag:
|
|
- Gang of Four
|
|
- Instantiation
|
|
- Lazy initialization
|
|
- Resource management
|
|
---
|
|
|
|
## Also known as
|
|
|
|
* Single Instance
|
|
|
|
## Intent of Singleton Design Pattern
|
|
|
|
Ensure a Java class only has one instance, and provide a global point of access to this singleton instance.
|
|
|
|
## Detailed Explanation of Singleton Pattern with Real-World Examples
|
|
|
|
Real-world example
|
|
|
|
> A real-world analogy for the Singleton pattern is a government issuing a passport. In a country, each citizen can only be issued one valid passport at a time. The passport office ensures that no duplicate passports are issued to the same person. Whenever a citizen needs to travel, they must use this single passport, which serves as the unique, globally recognized identifier for their travel credentials. This controlled access and unique instance management mirrors how the Singleton pattern ensures efficient object management in Java applications.
|
|
|
|
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 of Singleton Pattern in Java
|
|
|
|
Joshua Bloch, Effective Java 2nd Edition p.18
|
|
|
|
> A single-element enum type is the best way to implement a singleton
|
|
|
|
```java
|
|
public enum EnumIvoryTower {
|
|
INSTANCE
|
|
}
|
|
```
|
|
|
|
Then in order to use:
|
|
|
|
```java
|
|
var enumIvoryTower1 = EnumIvoryTower.INSTANCE;
|
|
var enumIvoryTower2 = EnumIvoryTower.INSTANCE;
|
|
LOGGER.info("enumIvoryTower1={}", enumIvoryTower1);
|
|
LOGGER.info("enumIvoryTower2={}", enumIvoryTower2);
|
|
```
|
|
|
|
The console output
|
|
|
|
```
|
|
enumIvoryTower1=com.iluwatar.singleton.EnumIvoryTower@1221555852
|
|
enumIvoryTower2=com.iluwatar.singleton.EnumIvoryTower@1221555852
|
|
```
|
|
|
|
## When to Use the Singleton Pattern in Java
|
|
|
|
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
|
|
|
|
## Real-World Applications of Singleton Pattern in Java
|
|
|
|
* The logging class
|
|
* Configuration classes in many applications
|
|
* Connection pools
|
|
* File manager
|
|
* [java.lang.Runtime#getRuntime()](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#getRuntime%28%29)
|
|
* [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--)
|
|
* [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--)
|
|
|
|
## Benefits and Trade-offs of Singleton Pattern
|
|
|
|
Benefits:
|
|
|
|
* Controlled access to the single instance.
|
|
* Reduced namespace pollution.
|
|
* Allows refinement of operations and representation.
|
|
* Permits a variable number of instances (more than one, if desired).
|
|
* More flexible than class operations.
|
|
|
|
Trade-offs:
|
|
|
|
* Difficult to test due to global state.
|
|
* Potentially more complex lifecycle management.
|
|
* Can introduce bottlenecks if used in a concurrent context without careful synchronization.
|
|
|
|
## Related Java Design Patterns
|
|
|
|
* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Often used to ensure a class only has one instance.
|
|
* [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Singleton pattern can be implemented using a Factory Method to encapsulate the creation logic.
|
|
* [Prototype](https://java-design-patterns.com/patterns/prototype/): Avoids the need to create instances, can work alongside Singleton to manage unique instances.
|
|
|
|
## References and Credits
|
|
|
|
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
|
|
* [Effective Java](https://amzn.to/4cGk2Jz)
|
|
* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
|
|
* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)
|
|
* [Refactoring to Patterns](https://amzn.to/3VOO4F5)
|