Singleton Design Pattern
Unlocking the Power of Singleton Design Pattern: One Instance to Rule Them All

Singleton Design Pattern

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

Chourouk LAHLAOUI

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 ??

Pavan Emani

Software Engineer || Frontend, Backend, Typescript, MERN || METI'24 Japan || Open Source

1 年

I think, this optimization works for linear processes only

要查看或添加评论,请登录

Ganesh Manchi的更多文章

  • Facade Design Pattern

    Facade Design Pattern

    Alice and Bob are watching a movie at Bob's place, enjoying the latest action flick on Bob's impressive home theater…

  • Factory Design Pattern

    Factory Design Pattern

    One sunny morning, Alice and Bob met at a bustling factory. Alice: Hi Bob, what brings you to this factory today? Bob:…

  • Decorator Design Pattern

    Decorator Design Pattern

    One sunny afternoon, Alice and Bob found themselves at their favorite coffee shop. Alice: Hi Bob, how's your day going?…

    2 条评论
  • Observer Design Pattern

    Observer Design Pattern

    One sunny afternoon, Alice and Bob decided to meet at their favorite park. Alice: Hi Bob, how's everything going? Bob:…

  • Strategy Design Pattern

    Strategy Design Pattern

    Bob came to Alice's house, and they have been playing Mortal Kombat for two hours. Alice: Hey Bob, we've played a lot…

  • Builder Design Pattern

    Builder Design Pattern

    Alice and Bob find themselves at a construction site once again. Alice : Hi Bob, what are you doing in this…

  • Coding culture in colleges :(

    Coding culture in colleges :(

    Hello, World! Note: If your college has a good coding culture, then skip this article. I want to share what I've…

    5 条评论
  • DSA vs CP

    DSA vs CP

    Hello World! One of the most confusing topics that often crosses our minds is the choice between Data Structures and…

社区洞察

其他会员也浏览了