What is the Singleton design pattern? How do you implement it in Java?
The Singleton design pattern ensures that a class has only one instance throughout the application’s lifecycle and provides a global point of access to that instance.
- Key points:
- Single Instance: Only one instance of the class is created.
- Global Access: The instance can be accessed globally, ensuring shared resources.
- Lazy Initialization: The instance is created only when it is needed, improving performance.
-
Implementation:
public class Singleton { private static Singleton instance; // Private constructor to prevent instantiation private Singleton() {} // Public method to provide access to the instance public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
- Explanation:
- Private Constructor: Prevents direct instantiation of the class.
getInstance()
Method: Checks if the instance is already created, and if not, creates it. The method uses double-checked locking for thread safety.
In summary, the Singleton pattern is used to control the creation of a class instance and ensure it is used globally, making it ideal for managing shared resources like database connections or configuration settings.