Singleton Design Pattern
Ganesh Manchi
Full Stack @TCS ? | Ex-SDE @ZopSmart ?? ( Go | Java | React ) ??♂? | 1900+ Knight @Leetcode ?? | Open Source @ Layer5 ?? | CS Engineer ??
One day, Alice and Bob meet at a coffee shop.
Alice : Hi Bob, how are you doing?
Bob : I'm good. What about your system design classes?
Alice : Today, I learned about the Singleton Design Pattern.
Bob : Singleton? What's its purpose?
Alice : The Singleton is a creational design pattern used to ensure there's only one instance of a class.
Bob : Why do we need just one instance?
Alice : It's incredibly useful in many applications, like logging, driver objects, caching, thread pools, and database connections.
Bob : Hold on a sec, I'm not quite grasping these terms.
Alice : No worries, I'll break it down. Imagine you buy a coffee machine to make your daily coffee. You don't buy a new one every day, right? In a similar way, consider a real world example with a logger. When working on a project, you need a logger to monitor the runtime workflow. A single logger instance is enough, you don't need multiple instances. By restricting it to just one instance, we improve system performance. This is called Lazy Initialization.
class Logger {
private static Logger logger;
private Logger() {}
public static Logger getLogger() {
if (logger == null) {
logger = new Logger();
}
return logger;
}
}
From outside, you can't create an object because the constructor is private. Instead, you call the getLogger() method to obtain an instance.
Bob : Wait a second. If the constructor is private, how do we create an object?
Alice : That's why we use the static keyword in the method signature, indicating that the method belongs to the class and can be called directly using the class name.
Logger logger = Logger.getLogger();
Bob : What about multithreading? If two threads execute the if (logger == null) condition simultaneously, won't they create two instances?
领英推荐
Alice : Yes, you're correct. In this case, you can add the synchronized keyword to the method signature to prevent two threads from accessing the method simultaneously.
public static synchronized Logger getLogger()
Bob : But once an instance is created, synchronization is no longer required, right?
Alice : Exactly. To address this, you can make the instance a static initializer, ensuring it's created by the JVM when the class is loaded. This is called Eager Initialization.
class Logger {
private static Logger logger = new Logger();
private Logger() {}
public static Logger getLogger() {
return logger;
}
}
Bob : But even if we're not using the instance, it will still be created, affecting performance for heavy objects.
Alice : To avoid these drawbacks, we can use Double Checked Locking.
class Logger {
private static volatile Logger logger = null;
private Logger() {}
public static Logger getInstance() {
if (logger == null) {
synchronized(Logger.class) {
if (logger == null) {
logger = new Logger();
}
}
}
return logger;
}
}
In this case, synchronization is applied only when the instance is null, ensuring that once an object is created, there's no need for synchronization. We also use the volatile keyword while creating the object, indicating that the variable is always read from and written to the main memory, allowing multiple threads to access it simultaneously and ensuring only a single instance is created.
Bob : It's a really nice concept. I've learned a lot about the Singleton design pattern today. I'll definitely try to integrate this concept into my projects. Thanks for the insights.
Alice : You're welcome, Bob. If you ever want to dive deeper into the world of design patterns, you know where to find me.
Bob : I'll keep that in mind. Until next time! Bye, Alice.
Alice : Goodbye, Bob.
Alice and Bob left the coffee shop after taking a final sip of their lattes, they will meet again soon...
Until then signing off with ? Ganesh
Data consultant @Avanade | Proficient in Python, SQL | Data Enthusiast | Passionate about Data Science | Ready to Dive into Real-world Projects ??
11 个月Thank you for this it was really helpful and insightful ??
Software Engineer || Frontend, Backend, Typescript, MERN || METI'24 Japan || Open Source
1 年I think, this optimization works for linear processes only