
Singleton Design Pattern
The singleton design pattern is used to restrict the instantiation of a class and ensures that only one instance of the class exists in the JVM. In other words, a singleton class is a class that can have only one object at a time per JVM instance.
Why We need Singleton Design Pattern:
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.
Where We Use :
It is used where only a single instance of a class is required to control the action throughout the execution. A singleton class shouldn't have multiple instances in any case and at any cost. Singleton classes are used for logging, driver objects, caching and thread pool, database connections.
getInstance()
method.Example
public class SingletonClass { private static final SingletonClass SINGLE_INSTANCE = new SingletonClass(); private SingletonClass() {} public static SingletonClass getInstance() { return SINGLE_INSTANCE; } }
public class SingletonClass { private static SingletonClass SINGLE_INSTANCE = null; private SingletonClass() {} public static SingletonClass getInstance() { if (SINGLE_INSTANCE == null) { synchronized(SingletonClass.class) { SINGLE_INSTANCE = new SingletonClass(); } } return SINGLE_INSTANCE; } }
Example Program :
class Database { private static Database dbObject; private Database() { } public static Database getInstance() { // create object if it's not already created if(dbObject == null) { dbObject = new Database(); } // returns the singleton object return dbObject; } public void getConnection() { System.out.println("You are now connected to the database."); } } class Main { public static void main(String[] args) { Database db1; // refers to the only object of Database db1= Database.getInstance(); db1.getConnection(); } } OUTPUT You are now connected to the Database.