Singleton Pattern
The Singleton pattern falls under the creational patterns category and is used when exactly one instance of a class is needed throughout the lifetime of an application. It is particularly useful when you want to control access to shared resources, such as a database connection or a logging service.
Key Features
- Private Constructor: The Singleton class has a private constructor to prevent direct instantiation from external classes.
- Static Instance: It contains a static member that holds the single instance of the class.
- Global Access Point: Provides a global access point to that instance via a public static method.
Implementing a Singleton
Let’s look at a basic implementation of a Singleton class in Java:
public class Singleton {
private static Singleton instance;
// Private constructor to prevent instantiation from other classes
private Singleton() {}
// Public static method to get the instance of the Singleton class
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
// Other methods and fields can be added here
}
Usage
To use the Singleton:
Singleton singleton = Singleton.getInstance();
Thread Safety
The basic Singleton implementation above is not thread-safe. To make it thread-safe, you can synchronize the getInstance()
method or use double-checked locking.
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
Variations
There are several variations of the Singleton pattern, including:
- Eager Initialization: The instance is created when the class is loaded.
- Static Initialization: Instance is created when the class is loaded, but it allows for exception handling.
- Thread-Safe Singleton: Ensures only one instance is created even in a multithreaded environment.
When to Use
Use the Singleton pattern when:
- You need to ensure that only one instance of a class exists.
- You want a single point of access to the instance from anywhere in your codebase.
- You want to control the instantiation of the class, possibly to manage resources more effectively.
Conclusion
The Singleton design pattern provides a way to ensure that a class has only one instance and provides a global point of access to that instance. It is widely used in scenarios where you need to manage shared resources or control how a single instance of a class is accessed throughout your application.