What is Singleton Design Pattern?
The Singleton Design Pattern is the simplest design pattern. Singleton Design Pattern means a Class will have only one Instance. A singleton pattern is used when you need to manage a shared resource.
Some Examples where Singleton Pattern is used:
- A printer spooler. Your application should only have a single instance of the spooler in order to avoid conflicting request for the same resource.
- A single Database connection is shared by multiple objects as creating a separate Database connection for each object is very costly task.
- Singletons are good in loggers because they broker access to, say, a file, which can only be written to exclusively.
Singleton Design Pattern Definition:
The singleton pattern is a design pattern that restricts the instantiation of a class to one object.
Singleton Design Pattern Program in Java:
package com.india.states;
public class Maharashtra {
// As the constructor is private, no one outside
//this class can create an object of this class
private Maharashtra() {
System.out.println("Maharashtra Created");
}
// only one instance of the class is created as the instance is static
private static Maharashtra mah=new Maharashtra();
// one instance will be shared only by this method
public static Maharashtra getInstance() {
return mah;
}
}
In the above program, Maharashtra class is a Singleton class. As it is a singleton Class only one instance of Maharashtra class should be created. Steps for implementing Singleton pattern:
- Make the constructor of Class private, which would restrict instance creation from outside the "Maharashtra" class.
- Create an instance inside the "Maharashtra" Singleton Class with "static" access specifier. Because static keyword specifies that the variable belongs to a class.
- Create a public method, using which other classes can get the same instance of "Maharashtra" class created above.
- To get instance of "Maharashtra" Singleton class from other class, call it using this syntax:
Maharashtra m=Maharashtra.getInstance();