-
Notifications
You must be signed in to change notification settings - Fork 0
Singleton Design Pattern
Devrath edited this page Feb 29, 2024
·
15 revisions
The singleton pattern restricts the initialization of a class to ensure that only one instance of the class can be created.
This design pattern ensures that an instance of a class can be created only once and make its instance globally available.
- This type of pattern signifies that there should be a single instance of object available which is having a global access point.
- This is useful in a scenario where we want to restrict the creation of multiple instances because wherever it's used it's the same state needed like a database or a network object.
- It's the
One above all
- Unlike other languages, defining a singleton is very simple
object ExampleSingleton {
fun exampleMethod() { }
}
When we want to use this singleton we add
ExampleSingleton.exampleMethod()
- By using the
Object
we can make sure the same instance of that object is available throughout the application.
- Even though it is the simplest of all the patterns, There is more possibility that it might be overused and result in scenario where it is hard to track the state and may become hard to maintain.
public class CacheManager {
private static volatile CacheManager instance;
// Private constructor to prevent external instantiation.
private CacheManager() { }
// Method to retrieve the singleton instance.
private static CacheManager getInstance() {
if (instance == null) {
synchronized (CacheManager.class) {
// Double-check to ensure a single instance is created.
if (instance == null) {
instance = new CacheManager();
}
}
}
return instance;
}
}
The volatile
keyword addresses the issues regarding thread safety and visibility in the multi-threaded environment.
- If we do not use
volatile
keyword, There is a possibility that multiple threads might see different values of the instance of this class due to thread caching. - Because of this multiple instances of singleton being created violating the singleton pattern.
- Using
volatile
ensures that the changes from one thread are visible to other threads ensuring an updated instance is available immediately.
- With the help of a singleton, We can share the state between two objects in the application.
- No composition overhead --> Because we just reach out to an object and use it, instead of building the composition of objects as a whole.
- It has a global static state, So all the problems associated with a global state apply to singleton as well.
- Singleton are hidden dependencies inside your classes.
- Singleton can form
circular dependencies
thus intercoupled in complex ways.
.