One, single case model theory
Single-case mode:
ensure that there is only one instance of a class, and that there is only one access point globally
Advantages:
1, because the singleton mode requires only one instance in the global, so can save more memory space
2, the global only one access point, can better control data synchronization, to avoid multiple occupancy
3, single case can be long-standing memory, reduce system overhead
Disadvantages:
1, the expansion of the singleton mode is more difficult
2, given a single case mode too much responsibility, to a certain extent violates the principle of single duty (one of six design principles)
3, the singleton mode is the concurrent Collaboration software module needs to be completed first, so it is not conducive to testing
4, the singleton mode in some cases will lead to resource bottlenecks
Application Scenarios:
1. Generate globally unique variables, such as serial numbers
2, access to global reuse of the only resources, such as disk, bus, etc.
3. A single object consumes too many resources, such as a database
4, System global unified management, such as the Task Manager under Windows
Second, the analysis of the __new__
# class demo:# def __init__ (Self, name):# self.name = name## def show_ Name (self): # print ("name is: {}". Format ( self.name)) ## if __name__ == ' __main__ ': ## d = demo ("Toby") # d.show_name () "refers to the description of the great God: This is the most common use of __init__. But __init__ is not actually the first method to be called when instantiating a class. when using an expression such as demo ("Toby") to instantiate a class, the first method to be called is actually the __new__ method. What is the __new__ method? The __new__ method accepts parameters that are the same as __init__, but __init__ is called after the class instance is created, and the __new__ method is the way to create the class instance. "' Class demo: def __new__ (cls, name): print ("call __new__") class_Instance = super (DEMO, CLS). __new__ (CLS) print (" New created class instance: ", class_instance) #打印一下 return class_ instance #返回Demon类的一个实例给__init__, and then uses this instance to invoke the __init__ method of the class def __init__ (self, name): #那__init__用什么来接收__new__返回来的类实例呢? The answer is Self print ("Init receives the class instance that new returns back:", self) # Print this self, which is a look at the instance print ("call __init__") produced by __new__ self.name = name def Show_name (self): print ("name is: {}". Format (self.name )) ## if __name__ == ' __main__ ': # d = demo ("Toby") # d.show_name () "Quotes the Great God's summary: so, __init__The main difference between and __new__ is that 1, __init__ is usually used to initialize a new instance, to control the initialization process, such as adding some properties, do some extra work that happens after the class instance is created. It is an instance-level method.     2, __new__ are typically used to control the process of generating a new instance. It is a class-level method. but with so much to say, what is the most common usage of __new__, and when do we need __new__? , the singleton pattern is a good example of "
Three, Singleton mode (case 1)
#coding: utf-8import threadingimport time# Here use method __new__ to implement Singleton mode Class singleton (object): # Abstract Single Example def __new__ (Cls, *args, **kwargs): if not hasattr (cls, "_instance"): orig = super (SINGLETON, CLS) cls._instance = orig.__new__ (Cls, *args, **kwargs) return cls._instance# bus Class bus (Singleton): lock = threading. Rlock () def senddata (self, data): self.lock.acquire () time.sleep (3) print ("Sending signal data ...", data) &nbsP; self.lock.release () #线程对象, in order to explain the meaning of the singleton, the bus object is instantiated in the run class visitentity ( Threading. Thread): my_bus = "" name = "" def getname (self): return self.name def setname (self, name): self.name = name def run (self): Self.my_bus = bus () self.my_bus.senddata (self.name) if __name__ == ' __main__ ': for i in range (3): print ("Entity {} begin to run ...". Format (i)) v = visitentity () v.setnAme ("Toby" +str (i)) v.start ()
Four, Singleton mode (case 2)
#使用__new__类方法来保证只有一个实例被创建出来class oneonly (object): _singleton = none def __new__ (Cls, *args, **kwargs): if not cls._singleton: #判断是否创建有实例, if not, call the super () function to create it cls._singleton = super (ONEONLY, CLS). __new__ ( CLS) #构造方法__new__被调用时, a new instance of the class is constructed return cls._ singleton# defines an ordinary class, with only the initialization method __init__class test: def __init__ (Self, name): self.name = name# defines a demo class and inherits the Oneonly class that implements the singleton pattern demo (oneonly): def __init__ (self, name): self.name = name def chage_name (Self, new_name): self.name = new_name def show_name (self): print ("name is: {}". Format (self.name)) if __name__ == ' _ _main__ ': #当通过OneOnly类中的构造方法构造实例时, always get exactly the same instance, same memory address # O1 = oneonly () # o2 = oneonly () # Print (O1) # print (O2) #通过Test类创建出来的两个实例t1和t2, is two different instances, The memory address is also different # t1 = test ("Toby") # t2 = test ("TTR") # print (T1) # print (T2) #Demo类继承了实现了单例模式的OneOnly类, so objects instantiated by the Demo class are the same object d1 = demo (" Toby ") d2 = demo (" TTR ") d3 = demo (" Laowang ") # by printing, their memory addresses are the same # print (D1) # print (D2) #发现打印出来的name都是 "Laowang", which seems to be the last to create an instance of the first two to cover the d1.show_name () d2.show_name () d3.show_name () # After the instance D1 modifies the name, then through the instance D3 and D2 to view, really also changed together. Which proves that they are indeed the same instance d1.chage_name ("Juck") d3.show_name () d2.show_name ()
Python design pattern--Singleton mode