hbutils.design.singleton

Overview:

Implement of singleton design pattern.

SingletonMeta

class hbutils.design.singleton.SingletonMeta[source]
Overview:

Meta class for singleton mode.

Example:
>>> class MyService(metaclass=SingletonMeta):
>>>     def get_value(self):
>>>         return 233
>>>
>>> s = MyService()
>>> s.get_value()    # 233
>>> s1 = MyService()
>>> s1 is s          # True

Note

In native singleton pattern, the constructor is not needed because only one instance will be created in the whole lifetime. So when SingletonMeta is used as metaclass, please keep the constructor be non-argument, or just ignore the __init__ function.

__call__()[source]

Call self as a function.

ValueBasedSingletonMeta

class hbutils.design.singleton.ValueBasedSingletonMeta[source]
Overview:

Meta class for value based singleton mode.

Example:
>>> class MyData(metaclass=ValueBasedSingletonMeta):
>>>     def __init__(self, value):
>>>         self.__value = value
>>>
>>>     @property
>>>     def value(self):
>>>         return self.__value
>>>
>>> d1 = MyData(1)
>>> d1.value       # 1
>>> d2 = MyData(1)
>>> d3 = MyData(2)
>>> d2 is d1       # True
>>> d2 is d3       # False

Note

This is an external case of singleton pattern. It can only contain one argument (must be positional-supported), which differs from the native singleton case.

__call__(value)[source]

Call self as a function.

SingletonMark

class hbutils.design.singleton.SingletonMark(value)[source]
Overview:

Singleton mark for some situation. Can be used when some default value is needed, especially when None has meaning which is not default.

Example:
>>> NO_VALUE = SingletonMark("no_value")
>>> NO_VALUE is SingletonMark("no_value")  # True

Note

SingletonMark is a value-based singleton class, can be used to create an unique value, especially in the cases which None is not suitable for the default value.

__eq__(other)[source]
Overview:

SingletonMark objects can be directly compared with ==.

Examples::
>>> mark1 = SingletonMark('mark1')
>>> mark1x = SingletonMark('mark1')
>>> mark2 = SingletonMark('mark2')
>>> mark1 == mark1
True
>>> mark1 == mark1x
True
>>> mark1 == mark2
False
__hash__()[source]
Overview:

SingletonMark objects are hash supported. can be directly used in dict and set.

__init__(mark)[source]
Overview:

Constructor of SingletonMark, can create a singleton mark object.

__repr__()[source]
Overview:

When you try to print a SingletonMark object, its mark content will be displayed.

Examples::
>>> mark1 = SingletonMark('mark1')
>>> print(mark1)
<SingletonMark mark1>
property mark
Overview:

Get mark string of this mark object.

Returns:
  • mark (str): Mark string