Singleton Pattern
A Singleton pattern is a type of pattern that is related to a creational type pattern. As it is identified from its name,i.e creational pattern means it works with object creation mechanisms. In simple words, we can say that it creates objects in a way that is suitable for a particular condition.
When there is a requirement to make sure that only a single object of a class needs to be instantiated then in this condition we use a singleton pattern. It is the responsibility of this created single instance to coordinate all the actions in the whole application.
Advantages
- Concurrent access to the resource is controlled by the singleton.
- It is the responsibility of singleton to ensure that there is an availability of only a single object in the controlled state in the whole application. To learn more about the singleton class, you can check out this Java tutorial.
Implementation
The existence of only one instance of the class is ensured.
Example:
- Java program for more clear understanding of the difference between static class and the singleton class
- This program mainly focuses on the example of the singleton pattern
- Java Program to illustrate the Difference Between import java.io.*;
- Creating class 1 with the name SingletonEagar
class SingletonEagar {
// simultaneously occurring variable declaration and definition
private static SingletonEagar instance = new SingletonEagar();
// class1 private constructor
private SingletonEagar () {}
// define a method for returning the instance of the class1
public static SingletonEagar getInstance() {
return instance;
}
}
- Creating the class with the name Singleton
class Singleton {
private static Singleton instance;
// class2 i.e . Singleton class private constructor.
private Singleton() { }
//returning an instance
public static Singleton getInstance() {
//check the condition
// creates a singleton class new object
// if the instance is null
if (instance == null) {
instance = new Singleton();
}
//returning the instance
return instance;
}
}
- Creating the class with the name SingletonSynchronizedMethod
class SingletonSynchronizedMethod {
private static SingletonSynchronizedMethod instance;
// class3 i.e . SingletonSynchronizedMethodclass private constructor.
private SingletonSynchronizedMethod() { }
//returning an instance
public static synchronized SingletonSynchronizedMethod
getInstance() {
//check the condition
// creates SingletonSynchronizedMethod class new object
// if the instance is null
if (instance == null) {
instance = new SingletonSynchronizedMethod();
}
//returning an instance
return instance;
}
}
- Creating the class with the name SingletonSynchronized
class SingletonSynchronized {
private static SingletonSynchronized instance;
// class3 i.e . SingletonSynchronized private constructor.
private SingletonSynchronized() { }
//returning an instance
public static SingletonSynchronized getInstance() {
// check the condition again
if (instance == null) {
synchronized(SingletonSynchronized.class)
{
//checking whether the instance is null or not
if (instance == null) {
instance = new SingletonSynchronized();
}
}
}
//returning an instance
return instance;
}
}
// Class 5
// Main class (SingletonExample)
public class Main {
// Main driver method
public static void main(String[] args) {
// create an instance of class 1 in the main method
SingletonEagar instance1 = SingletonEagar.getInstance();
// printing only message only
System.out.println( instance1 + " : Singleton Eager initialisation ");
//create an instance of class 2 in the main method
Singleton instance2 = Singleton.getInstance();
// printing only message
System.out.println(instance2 + " : Singleton Lazy initialisation ");
//create an instance of class 4 in the main method
SingletonSynchronized instance3 = SingletonSynchronized.getInstance();
// printing only message
System.out.println(instance3 + " : Synchronized Singleton");
}
}
Output
SingletonEagar@4ca8195f : Singleton Eager initialisation
Singleton@61baa894 : Singleton Lazy initialisation
SingletonSynchronized@768debd : Synchronized Singleton
Static Class
The nested classes that are declared static are known as static nested classes. The static class is a method of grouping different classes in java. The creation of static classes top-level is not allowed in java, it allows only nested classes. So, we can say that a static class is also defined as a static inner class or static nested class.
Also read - Static Method
Advantages
If we make the class static then it is possible to define the related or helper class within the class. An object reference can be used by it to access the private member of the enclosing class. The facility of a good namespace is provided by the static class for the nested class.
If the enclosing class is updated then after it, it is possible to update the static class even at the same location.
The static class is not loaded on loading of its enclosing class but it is loaded by the classloader at the first usage only.
Implementation
A static class can only be defined as an inner class or a nested class.
Just like other static members, all types of access modifiers such as private, public, protected or default can be used by static classes. Only the static members of its enclosing class accessed are allowed to the static class.
The static class is not able to directly access the non-static members of its enclosing class, so for this purpose, it uses the object of its enclosing class so that it can also interact with the non-static members.
Example
// Java program for more clear understanding of the difference between the singleton pattern and static class
// This java program mainly illustrates the example of the static class
// Classes import for the input-output
import java.io.*;
// creating the class with the class1 and it acts as a helper class
class Main {
// declaring an integer type variable and assigning it the value
static int a = 20;
public static void print() {
System.out.println(a);
}
// creating the second class as the inner static class
// it is allowed to access all the static data members and methods of the outer class
// but it can not access the non-static data members of the outer class.
static class InnerClass{
// inner class constructor
InnerClass(){
//printing the message
System.out.println("Inside the constructor of the InnerClass");
// displaying the value of the variable 'a' in the inner static class
System.out.println("'a' value inside the inner static class:" + a);
}
}
// main method
public static void main(String[] args)
{
// displaying the value of the variables inside the main method of the class
System.out.println(Main.a);
// calling the method print
Main.print();
// creating an object of the inner static class
Main.InnerClass myObj = new Main.InnerClass();
}
}
Output
20
20
Inside the constructor of the InnerClass
‘a’ value inside the inner static class:20
Difference Between Singleton Pattern and Static Class
Singleton Pattern | Static Class |
Singleton is defined as a design pattern. | Static is a method of grouping various classes in java. |
Once the object is created memory is allocated | Whenever any class member is accessed then at a time memory is allocated. |
Static or instance members are allowed during the implementation of the singleton. | It has static members only. |
Implementation of any other base class or any other interface is possible in singleton. | Implementation of any interface or any base class is not allowed in static classes. |
We can use singleton classes as a parameter of the method. | We cannot use static as a parameter of the method. |
Heap memory is used for the implementation of the singleton pattern. | Stack memory is used for the implementation of the static class. |
As heap memory is used in singleton pattern so it works within the scope of Garbage Collector. | It does not work within the scope of Garbage Collector as stack memory is used in it. |
Singleton works on the concept of OOPS so it supports the implementation of the Dependency Injection (DI). | There is no implementation of Dependency Injection (DI) as DI is interface-driven. |
We cannot define singleton as a language feature as it is only an architectural pattern. | Generally static is a language feature, we cannot use the term architectural pattern for it. |
There may be chances of object disposal. | There is no possibility of disposal of objects as there is no creation of instances. |