Hi My friends, in this small tutorial we will discuss the Singleton design pattern and I will show you an implementation in JAVA.
As you may already know there are three types of design patterns: Creational, behavioral and structural. Singleton is among the creational patterns and it is the easiest one to learn.
Why Singleton? :
- The need to have one and only instance of a class during the execution of the application.
- The instance should not be accessible only from a method of the class.
Steps to implement the design :
- Make the constructor of the class that you want it to be singleton private.
- Create a public static method with return type of Class, this method will be responsible for the instantiation of the class.
- Add a private static attribute that represents the instance of the class .
The following code represents an implementation of this design pattern.
public class SingletonClass {
private static SingletonClass instance = null;
// the constructor is private
private SingletonClass() {
}
// the method responsible for the instantiation
public static SingletonClass getInstance()
{
if(instance == null) {
instance = new SingletonClass();
}
return instance;
}
}
public class TestSingletonClass {
public static void main(String[] args) {
//create the first instance
SingletonClass instance = SingletonClass.getInstance();
System.out.println(instance);
//create the second instance
SingletonClass instancetwo = SingletonClass.getInstance();
System.out.println(instancetwo);
// the outut of the two instances is the same .
}
}