Singleton mode 1. What are single cases?
Make sure that there is only one instance of a class, and instantiate it yourself and provide this instance to the entire system, which is called a singleton class, and the singleton pattern is an object-creation pattern.
So what is the use of the singleton model? As an example of a common singleton pattern, we usually use a computer that has a recycle Bin, in the entire operating system, the Recycle Bin can only have one instance, the entire system uses this unique instance, and the Recycle Bin provides its own instance, so the Recycle Bin is a singleton mode application.
2. Create a singleton-guaranteed only 1 objects
class Singleton(object): __instance = None def __new__(cls, name, age): # 如果类属性__instance的值为None,那么就创建一个对象 if not cls.__instance: cls.__instance = object.__new__(cls) # 如果已经有实例存在,直接返回 return cls.__instancea = Singleton("Zhangsan", 18)b = Singleton("lisi", 20)print(id(a))print(id(b))a.age = 30 # 给a指向的对象添加一个属性print(b.age) # 获取b指向的对象的age属性
Operation Result:
2946414454432294641445443230
3. Create a singleton and perform only 1 timesInitMethod
class Singleton(object): __instance = None __first_init = False def __new__(cls, name, age): if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance def __init__(self, name, age): if not self.__first_init: self.name = name self.age = age Singleton.__first_init = Truea = Singleton("Zhangsan", 18)b = Singleton("lisi", 20)print(id(a))print(id(b))print(a.name, a.age)print(b.name, b.age)a.age = 50print(b.age)
Operation Result:
22066402853442206640285344Zhangsan 18Zhangsan 1850
Python implementation Singleton mode