Singleton Pattern
Intent:
Ensure a class has only one instance and provide a global point of access to it.
When to Use:
When exactly one object is needed to coordinate actions across a system (e.g., logging, configuration, caching).
Key Characteristics:
- Ensures a single instance
- Provides a global access point
- Thread-safe in multi-threaded environments (with locking mechanism)
Implementation Example (Python, Thread-safe):
# singleton.py import threading class Singleton: __instance = None __lock = threading.Lock() def __new__(cls, *args, **kwargs): if cls.__instance is None: with cls.__lock: # Thread-safe instantiation if cls.__instance is None: cls.__instance = super().__new__(cls) return cls.__instance if __name__ == "__main__": instance1 = Singleton() print("Instance 1:", instance1) instance2 = Singleton() print("Instance 2:", instance2) print("Are both instances the same?", instance1 is instance2)# singleton.py import threading class Singleton: __instance = None __lock = threading.Lock() def __new__(cls, *args, **kwargs): if cls.__instance is None: with cls.__lock: # Thread-safe instantiation if cls.__instance is None: cls.__instance = super().__new__(cls) return cls.__instance if __name__ == "__main__": instance1 = Singleton() print("Instance 1:", instance1) instance2 = Singleton() print("Instance 2:", instance2) print("Are both instances the same?", instance1 is instance2)
Output:
Instance 1: <__main__.Singleton object at 0x...> Instance 2: <__main__.Singleton object at 0x...> Are both instances the same? True
Summary:
- Guarantees a single instance
- Useful for shared resources (loggers, config managers)
- Thread safety is important in concurrent environments