This is a type of Creational design pattern. The purpose of this pattern is to restrict the creation of instance of a particular class to one. Such a class is called a singleton class.
We should consider making a class singleton if the class needs to execute a set of expensive one time operations before it can perform any of its behavior operation and multiple calls to its behavior can use the same loaded resources over and over again.
In java, we implement singleton pattern by making the class's constructor private. This restricts the public(outside) access to create class instance. Then we provide a public static method to have access to the single class instance created inside the same method.
Let us take an example.
// BEGIN - Singleton Sample Code
package com.teawithjava.patterns.public class KeepMeSingle {
private static KeepMeSingle instance;
private KeepMeSingle() {
//Load expensive resources to be used by the class later
System.out.println("Singleton instance of class KeepMeSingle created");
}
public static KeepMeSingle getSingleton() {
if (null == instance) {
System.out.println("Singleton instance is not created yet. So a KeepMeSingle instance will be created");
instance = new KeepMeSingle();
}
System.out.println("Retirned the Singleton instance of class KeepMeSingle");
return instance;
}
public void method1() {
System.out.println("Hello There, This is the Singleton instance reporting :) !!!");
}
public void method2() {
System.out.println("Hello There, This is the same Singleton instance reporting again :) !!!");
}
//Test Main Method
public static void main(String[] args) {
KeepMeSingle.getSingleton().
KeepMeSingle.getSingleton().
}
}
// END - Singleton Sample Code
Code Explanation:
- Create a class KeepMeSingle and make its constructor private
- Create private static reference variable of KeepMeSingle and assign it to null. This is because we want to have only one instance of KeepMeSingle and reference it using this static variable.
- Create public static method getSingleton() to provide handle/reference to the outside classes. Notice we are checking if the static instance is null. If so we create an instance and assign it. Finally we return the singleton instance.
- method1() and method2() and some methods of the KeepMeSingle class for testing.
- In main() method, the first call to static method getSingleton() of KeepMeSingle get its instance created(calls constructor) and then calls method1().
- In main() method, second call to static method getSingleton() of KeepMeSingle returns the same instance created(does not call constructor) and then calls method2().