Your One-and-Only Object
In essence, the Singleton Design Pattern acts as your city’s mayor’s office, ensuring centralized control, efficient resource management, and a single point of contact for vital functionalities within your application.
getInstance()
.getInstance()
method to access the singleton object and utilize its functionalities.class Singleton:
_instance = None # Class variable to hold the instance
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self, value):
self.value = value
# Client code
singleton1 = Singleton(10)
singleton2 = Singleton(20) # Won't create a new instance
print(singleton1.value) # Output: 10
print(singleton2.value) # Output: 10 (same instance)
print(singleton1 is singleton2) # Output: True (same object)