Is there a simple, elegant...
Is there a simple, elegant...
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[3][4].
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:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class Singleton:
pass
This method is intuitive and additive, allowing for clear modifications without altering the class structure itself[4].
Implementing singleton behavior in a base class from which other singletons can inherit is another approach. This method uses the __new__
method to control instance creation.
class SingletonBase:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls, *args, **kwargs)
re...
expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào