Singleton design pattern and multi Embodiment Mode
What is a design pattern
Design patterns are solutions to common problems faced by developers in the development process
These solutions are numerous developers through trial and error for a long period of time summary out
Singleton
Only a single class object is created
Multi-pattern
A class can have multiple objects are created
## 平时我们使用的都是多例模式
class custom():
pass
c1 = custom()
c2 = custom()
print(c1) # <__main__.custom object at 0x0000020305FEA248>
print(c2) # <__main__.custom object at 0x0000020305FEA188>
print(c1 is c2) # False
## 我们可以通过他们的内存地址来判断是否是同一个实例也可以使用is判断
Create a singleton instance
The method of binding by class
class custom(): # 记录实例对象 _is_create = None def __init__(self, name): self.name = name # 通过类方法创建实例 @classmethod def create_class(cls, name): # 如果没有对象 if not cls._is_create: # 创建对象并将对象赋值给_is_create cls._is_create = cls(name) return cls._is_create # 通过类方法来创建类的实例化对象 c1 = custom.create_class('张三') c2 = custom.create_class('李四') print(c1 is c2) # False
By decorator
def wer(func): # 记录多个类的实例化对象 _instance = {} def inner(*args, **kwargs): # 如果没有对象 if func not in _instance: # 创建对象并将对象赋值给_instance _instance[func] = func(*args, **kwargs) return _instance[func] return inner @wer class Myclass(object): pass m1 = Myclass() m2 = Myclass() print(m1 is m2) # True
By yuan class
class Mytype(type): # 当实例化类的时候会调用元类的__call__方法 def __call__(self, *args, **kwargs): # 如果实例化的类中没有_instance属性就创建一个实例化对象 if not getattr(self, '_instance'): # 创建”空“对象赋值给_instance self._instance = self.__new__(self) # 为“空”对象初始化 self._instance.__init__(*args, **kwargs) return self._instance class Foo(metaclass=Mytype): _instance = None f1 = Foo() f2 = Foo() print(f1 is f2)
Import in python code module is an object, but the object is to import only once, whether you are importing a few times.
In Python module is a special single-mode embodiment.