Course contentsShow
← Software Engineering
Lesson 232 of 1,9337. Creational Design PatternsFree lesson

When Singleton is Appropriate

Identify legitimate use cases for Singleton, such as logging, configuration, and resource pools, where single instances make sense.

When Singleton is Appropriate

What you'll learn: You'll discover the legitimate scenarios where the Singleton pattern solves real problems without creating tight coupling nightmares.

The Right Time for a Single Instance

While Singleton has earned a reputation as an anti-pattern, there are genuine situations where having exactly one instance of a class makes sense. The key is distinguishing between "we only need one" (which Dependency Injection handles better) and "there must be only one for correctness."

Think of Singleton like a city's electrical grid control center. You don't want multiple control centers making conflicting decisions about the same power lines—one coordinated authority is essential for safety and consistency.

Legitimate Singleton Use Cases

Logging Systems: A single logger ensures all log entries are written consistently to the same destination without file conflicts or resource contention. Multiple logger instances might corrupt log files or waste system resources.

Configuration Management: Application settings loaded once at startup—database URLs, API keys, feature flags—don't need multiple copies floating around. One configuration object provides a single source of truth.

Resource Pools: Connection pools (database, network) or thread pools manage scarce system resources. Having multiple pools defeats the purpose of controlled resource allocation and can lead to exhaustion.

Hardware Interface Access: When your code interfaces with physical hardware (printer, scanner, GPU), the hardware itself enforces singularity. A Singleton mirrors this physical constraint.

The Litmus Test

Ask yourself: Does having multiple instances create actual problems—race conditions, resource waste, or inconsistent state? Or are you just avoiding passing a parameter? If it's the latter, use Dependency Injection instead.

Key Takeaway: Singleton is appropriate when managing shared resources or enforcing system-wide coordination, particularly for logging, configuration, and resource pools where a single point of control prevents conflicts and ensures consistency.