Source code for cosapp.patterns.singleton
[docs]
class Singleton(type):
"""
Metaclass for singleton pattern.
Reference
---------
https://refactoring.guru/design-patterns/singleton
Examples
--------
>>> class MyClass(metaclass=Singleton):
>>> pass
>>>
>>> m1 = MyClass()
>>> m2 = MyClass()
>>> assert m1 is m2
"""
def __init__(cls, name, bases, attrs):
super().__init__(name, bases, attrs)
cls.__instance = None
# Ensure instance-level copy/deepcopy return the singleton instance
# Note: implementing __copy__ and __deepcopy__ at metaclass level
# is unnecessary, as it does not affect instance behaviour.
cls.__copy__ = lambda self: self
cls.__deepcopy__ = lambda self, memo=None: self
def __call__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = super().__call__(*args, **kwargs)
return cls.__instance