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.
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) # Trueclass 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) # 10Last updated