Instantiation Supplement:
One, single case mode
1. Introduction of single-case mode
The singleton pattern (Singleton pattern) is a commonly used software design pattern that is primarily intended to ensure that only one instance of a class exists. A singleton can come in handy when you want the entire system to have only one instance of a class. The following four types of singleton patterns are common:
Singleton Mode 1: module
The module is a natural singleton mode, since the first call to the module will be compiled into a. pyc file, which will load the. pyc file directly during a subsequent call.
Singleton Mode 2: Class @classmethod
(1) Unable to support multithreading situation:
classSingleton (object):def __init__(self):#Analog IO blocking ImportTime Time.sleep (1) @classmethoddefInstance (cls,*args,**Kwargs):if notHasattr (Singleton,"_instance"): Singleton._instance=singleton (*args,**Kwargs)returnsingleton._instance#Applicationobj1=singleton.instance () obj2=singleton.instance ()Print(OBJ1,OBJ2)#<__main__. Singleton object at 0x000002c49db6c5f8> <__main__. Singleton object at 0x000002c49db6c5f8>
(2) Support multi-threading situation
ImportThreadingclassSingleton (object): _instance_lock=Threading. Lock ()def __init__(self):ImportTime Time.sleep (1) @classmethoddefInstance (cls,*args,**Kwargs):if notHasattr (Singleton,"_instance"): With Singleton._instance_lock:if notHasattr (Singleton,"_instance"): Singleton._instance=singleton (*args,**Kwargs)returnsingleton._instance#Applicationdeftask (n): obj=singleton.instance ()Print(n,obj) forIinchRange (10): T=threading. Thread (target=task,args=[I,]) T.start ()
Singleton mode 3: Based on __new__
(1) multithreading is not supported
classSingleton (object):def __init__(self):Pass def __new__(CLS, *args, * *Kwargs):if notHasattr (Singleton,"_instance"): Singleton._instance=object.__new__(cls,*args,**Kwargs)returnsingleton._instance#application: Class instantiation will first execute the __new__ methodObj=singleton ()
(2) Support multi-threading situation
ImportThreadingclassSingleton (object): _instance_lock=Threading. Lock ()def __init__(self):ImportTime Time.sleep (1) def __new__(CLS, *args, * *Kwargs):if notHasattr (Singleton,"_instance"): With Singleton._instance_lock:if notHasattr (Singleton,"_instance"): Singleton._instance=object.__new__(cls,*args,**Kwargs)returnsingleton._instance#application: Class instantiation will first execute the __new__ methoddeftask (n): obj=Singleton ()Print(n,obj) forIinchRange (10): T=threading. Thread (target=task,args=[I,]) T.start ()
Singleton Mode 4: Based on Metaclass
The analysis is as follows:
""" 1. The object is the class creation, when the object is created, the __init__ method of the class is executed automatically, and the object () executes the __call__ method of the Class 2. Class is the type created, the class is created when the __init__ method of the type is automatically executed, and the class () executes the type's __call__ method (__new__ method of Class, __init__ method of Class) # No. 0 Step: Execute the type's __init__ method "Class is the object of type" class Foo: def __init__ (self): pass def __ Call__ (self, *args, **kwargs): pass# 1th Step: Executes the __call__ method of type # 1.1 calls the Foo class (the object of type) __new__ method, which is used to create the object. # 1.2 invokes the __init__ method of the Foo class (the object of type), which is used to initialize the object. obj = Foo () # 2nd Step: __call__ method for executing food obj () "" "
Singleton Mode Example:
ImportThreadingclassSingletontype (type): _instance_lock=Threading. Lock ()def __call__(CLS, *args, * *Kwargs):if notHasattr (CLS,"_instance"): With Singletontype._instance_lock:if notHasattr (CLS,"_instance"): Cls._instance= Super (SINGLETONTYPE,CLS).__call__(*args, * *Kwargs)returncls._instanceclassFoo (metaclass=singletontype):def __init__(self,name): Self.name=Name
Obj1= Foo ('name') Obj2= Foo ('name')Print(OBJ1,OBJ2)
2. Single Case mode application
This is mainly for our previous chapter of the database connection pool, and the combination of the singleton mode, so that any user or view when the database is called, do not need to repeatedly instantiate database connection pool object, mainly described as follows:
ImportPymysqlImportThreading fromDbutils.pooleddbImportPOOLEDDBclassSingletondbpool (object): _instance_lock=Threading. Lock ()def __init__(self): Self.pool=Pooleddb (creator=Pymysql, MaxConnections=6, mincached=2, maxcached=5, maxshared=3, blocking=True, Maxusage=None, Setsession=[], Ping=0, host='127.0.0.1', Port=3306, the user='Root', Password='123', Database='Pooldb', CharSet='UTF8' ) def __new__(CLS, *args, * *Kwargs):if notHasattr (Singletondbpool,"_instance"): With Singletondbpool._instance_lock:if notHasattr (Singletondbpool,"_instance"): Singletondbpool._instance= object.__new__(CLS, *args, * *Kwargs)returnsingletondbpool._instancedefConnect (self):returnSelf.pool.connection ()
An example of a reference to a singleton module for the database connection pool above is as follows:
def run (): = Singletondbpool () # instantiation of con = pool.connect () # Create connection # ......... con.close () # Close, not really close if__name__' __main__': run ()
Second, custom session
Reference Document: Https://python-team.gitbooks.io/flask-doc/content/di-si-zhang-kuo-zhan/11-nei-zhisession-yuan-li.html
Python Road _flask Framework _ single case mode and session principle