Singleton Pattern — Explained with Examples
Singleton is a creational pattern that ensures a class has only one instance and provides a global access point to that instance.
Singleton is one of the Gang of Four (GoF) design patterns. It restricts a class to a single instance and provides a static method to access it. The constructor is typically private or protected to prevent external instantiation.
Why Singleton Matters
Certain resources should have exactly one instance: a database connection pool, a logger, a configuration manager, or a thread pool. Creating multiple instances would waste resources, cause conflicts, or produce inconsistent state. Singleton guarantees controlled access to a shared resource.
Real-World Analogy
A country has only one president. If everyone could create their own president, you’d have chaos — conflicting orders, no single authority. Instead, there’s a single point of contact for presidential decisions. Similarly, Singleton ensures a single authority for shared resources.
Example: Singleton in Python
class ConfigurationManager:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._config = {}
return cls._instance
def set(self, key, value):
self._config[key] = value
def get(self, key):
return self._config.get(key)
# Both variables point to the same instance
config1 = ConfigurationManager()
config2 = ConfigurationManager()
config1.set("db_host", "localhost")
print(config2.get("db_host")) # Output: localhost
print(config1 is config2) # Output: TrueWhen to Avoid Singleton
Singletons introduce global state, which makes unit testing difficult (tests can’t isolate state) and hides dependencies. Consider Dependency Injection instead — it provides the same single-instance benefit without the global state drawback.
Related Terms
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro