Is there a simple, elegant way to define singletons?
Is there a simple, elegant way to define singletons?
Yes, there are several simple and elegant ways to define singletons in Python, each with its own advantages and considerations. Here are some of the most commonly used methods:
A metaclass can control the instantiation of a class. By overriding the __call__ method in the metaclass, you can ensure that only one instance of a class is created.
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
pass
This method is highly readable and reusable, and it's easy to test because you can mock the metaclass during testing.
A decorator can be used to wrap a class and control its instantiation. This approach is less intrusive and can be easily added or removed from a class.
def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.