Implementing Singleton pattern with Python
There are many ways to implement Singleton pattern in Python, and the following two common methods are given.
1. Use module level variables:
python
class Singleton:
Single instance class
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
#Usage examples
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2) # True
2. Use decorators:
python
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class Singleton:
Single instance class
pass
#Usage examples
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2) # True
Both of the above methods can implement the Singleton pattern to ensure that there is only one instance in the program. The implementation principle is through rewriting`__ New__` Method to control the instantiation process and ensure that only one instance is created.