Singleton Pattern – More Than “One Object”

In many systems, there are things that logically should exist only once.
A logger. A configuration manager. A connection pool.

If two parts of the system use different loggers or different configs, things break in subtle ways.

The problem is not “how to create one object”.
The problem is how to control object creation across the entire system.

class Config {
    public static Config instance = new Config();
}
  • This technically gives one object
  • But:
    • It’s created even if never used
    • You can’t control initialization
    • Hard to test
    • Hard to change later

What if creating this object is expensive?
What if it depends on runtime configuration?
What if tomorrow we want two configs for testing?

That is where Singleton is used

Singleton is not about “only one object”.
It is about centralizing and controlling the creation of an important dependency.

Singleton pattern has :

  • Private constructor → no one can new it
  • Controlled access point → you decide when and how it is created
  • Lazy initialization → created only when needed
class Config {
    private static Config instance;

    private Config() {}

    public static Config getInstance() {
        if (instance == null) {
            instance = new Config();
        }
        return instance;
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top