23. Singleton Pattern
The Singleton Pattern ensures that a class has only one instance throughout the application's lifetime and provides a global point of access to that instance.
1. Classic Singleton using a Private Class Variable
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2) # True2. Singleton with Initialization
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls)
cls._initialized = False
return cls._instance
def __init__(self, value):
if not self._initialized:
self.value = value
self._initialized = True
obj1 = Singleton(10)
obj2 = Singleton(20)
print(obj1 is obj2) # True
print(obj1.value) # 10
print(obj2.value) # 103. Singleton Using a Decorator
4. Singleton Using a Metaclass
5. Thread-Safe Singleton
6. Singleton with Global Instance
7. Singleton Using a Module
8. Singleton with Weak References
9. Singleton Using Borg Pattern (Shared State)
10. Config Manager Singleton Example
These examples demonstrate various ways to implement the Singleton Pattern in Python, providing flexibility for different use cases such as thread safety, module-level singletons, and shared state.
Last updated