2022-03-10 03:20:04 +00:00
|
|
|
class SingletonMeta(type):
|
|
|
|
"""
|
|
|
|
The Singleton class can be implemented in different ways in Python. Some
|
|
|
|
possible methods include: base class, decorator, metaclass. We will use the
|
|
|
|
metaclass because it is best suited for this purpose.
|
|
|
|
"""
|
|
|
|
|
|
|
|
_instances = {}
|
|
|
|
|
|
|
|
def __call__(cls, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Possible changes to the value of the `__init__` argument do not affect
|
|
|
|
the returned instance.
|
|
|
|
"""
|
|
|
|
if cls not in cls._instances:
|
|
|
|
instance = super().__call__(*args, **kwargs)
|
|
|
|
cls._instances[cls] = instance
|
2022-09-13 10:30:18 +00:00
|
|
|
else:
|
|
|
|
assert len(args) == 0 and len(
|
|
|
|
kwargs) == 0, f'{cls.__name__} is a singleton class and a instance has been created.'
|
2022-03-10 03:20:04 +00:00
|
|
|
return cls._instances[cls]
|