Lesson 43: Design Pattern: Singleton

13 Aug 2026 1 min Swarnil Singhai

Singleton guarantees exactly one instance of a class exists application-wide — useful for shared resources like a configuration loader.

Real-time example

An app's AppConfig is loaded from a file once and reused everywhere, instead of re-reading the file on every access.

class AppConfig {
    private static final AppConfig INSTANCE = new AppConfig();
    private Map<String, String> settings = Map.of("env", "production");

    private AppConfig() {}
    static AppConfig getInstance() { return INSTANCE; }
}
System.out.println(AppConfig.getInstance().settings.get("env"));

What's happening

The private constructor prevents new AppConfig() from outside — getInstance() is the only way to get the one shared instance.

Singletons are convenient but make unit testing harder (global shared state) — use dependency injection where possible instead.

Advertisement