Singleton Pattern
Published Nov 10, 2021Updated Jan 18, 2023
Contribute to Docs
The singleton pattern ensures a class has only one object instantiated during the program’s lifecycle. It is used to guarantee the control of a resource through its implementation.
UML Design
Java Example
Generally, singletons are lazily loaded and ensure thread safety. Below is a Java example outlining the most basic form of a singleton. The .getInstance()
method creates a new instance (if one does not exist), and the synchronized
keyword ensures two threads can not use this method at the same time.
public class Singleton {// The singleton instance to be returned by getInstance()private static Singleton instance = null;// Constructor is made private to stop creation through 'new' keyword outside of getInstance()private Singleton() {}// Returns instance when calledpublic static synchronized Singleton getInstance() {// Creates new instance if none existsif (instance == null) {instance = new Singleton();}return instance;}}
All contributors
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.