Creational Design Pattern
![](https://codelido.com/assets/files/2022-12-17/1671306491-155131-single-ton-design-pattern-1.jpg)
Definition
The singleton pattern belongs to the category of creational patterns within the realm of design patterns. A less frequently used name is simply “singleton”. Its purpose is to prevent more than one object from being created by a class. This is achieved by creating the desired object in a class and retrieving it as a static instance. The singleton is one of the simplest but most powerful patterns in software development.
Characteristics
- If the singleton design pattern was used to create an instance of a class, then the pattern makes sure that it really only remains with this single instance.
- The singleton makes this class of software globally accessible. In different programming languages, there are different methods to achieve this.
- To make sure that it remains with only one unique instance, users must be prevented from creating new instances. This is achieved by the constructor declaring the pattern as “private”.
- This means that only the code in the singleton can instantiate the singleton itself. In effect, this guarantees that only one and the same object can reach the user. If this instance already exists, no new instance is created.
UML Diagram
![](https://codelido.com/assets/files/2022-12-17/1671302501-47524-image.png)
Code
public class SingleObject
{
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
instantiated
private SingleObject()
{
}
//Get the only object available
public static SingleObject getInstance()
{
return instance;
}
public void showMessage()
{
System.out.println("Hello World!");
}
}
public class SingletonPatternDemo
{
public static void main(String[] args)
{
//Get the only object available
SingleObject object = SingleObject.getInstance();
//show the message
object.showMessage();
}
}
Advantages
->If many people have the same requirement, then it is not required to create a separate object for every requirement.
->Improved performance.
->Improved memory utilization.
Disadvantages
->It can be difficult to unit test the code.
->It can lead to tightly coupled code.
->If the single Instance of the object becomes corrupted, the entire system is compromised.