Singleton Design Pattern
Sometimes it’s important for some classes to have exactly one instance. There are many objects we only need one instance of them and if we, instantiate more than one, we’ll run into all sorts of problems like incorrect program behavior, overuse of resources, or inconsistent results.
There are only two points in the definition of a singleton design pattern :
- There should be only one instance allowed for a class and
- We should allow global point of access to that single instance.
From the definition, it seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. The implementation of Java Singleton pattern has always been a controversial topic among developers. Here we will learn about Singleton design pattern principles, different ways to implement Singleton design pattern and some of the best practices for its usage.
Lazy initialization will be beneficial when we want to delay the initialization until it is not needed. because if we use eager initialization and if initialization fails there is no chance to get the instance further while in lazy initialization we may get it in second chance. In Lazy initialization we will not get instance until we call getInstance () method while in eager initialization it creates instance at the time of class loading.
Example
package com.loopandbreak.singleton; /** * This class will implement basic Singleton design pattern */ public class SingletonPattern { private static SingletonPattern singletonPattern = new SingletonPattern(); /* * Constructor is made private */ private SingletonPattern() { System.out.println("Creating Object....."); } public static SingletonPattern getInstance() { return singletonPattern; } public static void main(String[] args) { SingletonPattern object1 = SingletonPattern.getInstance(); SingletonPattern object2 = SingletonPattern.getInstance(); print(object1); print(object2); } private static void print(SingletonPattern object) { System.out.println("Hashcode of object is " + object); } }
Output
Creating Object..... Hashcode of object is com.loopandbreak.singleton.SingletonPattern@1b6d3586 Hashcode of object is com.loopandbreak.singleton.SingletonPattern@1b6d3586
In the above example we have called getInstance() two times, but hashcode is same for both the class. It means that only one instance is created and on every call this instance is returned