Singleton design pattern
Sometimes we want just a single instance of a class to exist in the system
We use the Singleton pattern for achieving the below.
To make sure that there can be one and only one instance of a class and provide global point of access to it.
The Singleton pattern ensures that only one instance of a class is created.
All objects that use an instance of that class use the same instance.
Here is the implementation of a Singleton design pattern:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class Singleton { private static Singleton instance; //To make sure that multiple objects are getting created with new keyword private Singleton() { } //To get the instance of the singleton class public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } public Object clone() throws CloneNotSupportedException { /*For preventing the singleton object from being cloned*/ throw new CloneNotSupportedException(); } // other methods here } |
The singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that singleton instances are created only when needed.
Recommended Books
Leave a Reply