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;}}
Contribute to Docs
- 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.
Learn more on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours