Singleton mode is to tell you that there is only one object
(1) scenario where a singleton mode is not applicable
#单例模式就是告诉你, there is actually only one object class Person: def __init__ (self,name,age): self.name = Name self.age = "Age" assumes such a scenario , there is a class dedicated to creating people, in every instantiation we create a person, we want to give this person's name, age, basic, height, and so on, this mode is obviously not suitable for a singleton mode, because there are multiple objects, and each object is encapsulated different properties, Singleton mode can only allow the creation of a person, So does not apply ' ' ' Xiaoming=person (' Xiao Ming ', ') Xiaoyue =person (' Xiao Yue '), Xiaohong = person (' Little Red ', 28)
(2) When the data encapsulated in all instances is the same, the singleton mode can be used, for example
Class Person2: def __init__ (self): self.name = ' Jay ' self.age = + def f1 (self): pass def f2 ( Self): passxiaoming =person2 () xiaoming.f1 () "created two identical instances, wasting memory, this scenario can use Singleton mode" ' Xiaoming = Person2 () xiaoming.f1 ()
There's also a classic usage scenario, a link between the machines database
Under this singleton pattern, suppose to create a connection pool
Import Randomclass connectionpool: def __init__ (self): #链接数据库需要的通行证 self.ip= ' 2.2.2.2 ' self.port= 6379 self.pwd = ' 654321 ' self.username = ' Jay ' #去链接 self.conn_list = [1,2,3,4,5,6] #假设创建了6个链接 def get_connection (self): #获取链接, here specifically every write, just an example of R = Random.randrange (1,6) return Rpool=connectionpool ( )
For I in range (6): conn = Pool.get_connection () #进行链接, it's good to go in and get a connection at each link, without instantiating an object.
So the person each time in the operation is a singleton mode, with an instance to link, but if more than one colleague open this file, still will instantiate a number of the same object, wasting memory
We can do this so that every call in memory seems to fetch the instance that was created for the first time.
Import randomclass connectionpool: __instance = none# default is None def __init__ (self): #链接数据库需要的通行证 self.ip= ' 2.2.2.2 ' self.port= 6379 self.pwd = ' 654321 ' self.username = ' Jay ' #去链接 self.conn_list = [ 1,2,3,4,5,6] #假设创建了6个链接 @staticmethod def get_instance (): if connectionpool.__instance: #如果实例已经存在, Returns the created instance return connectionpool.__instance else: connectionpool.__instance = ConnectionPool () #如果是第一次调用, execute the function, instantiate a connection pool return connectionpool.__instance# Assign the object to the static field def get_ Connection (self): #获取链接 r = Random.randrange (1,6) return robj1= connectionpool.get_instance () print ( OBJ1) obj2= connectionpool.get_instance () print (OBJ2) obj3= connectionpool.get_instance () print (OBJ3) obj4= Connectionpool.get_instance () print (OBJ4)
Results
(3) Creating a singleton mode for a Web site
Here is a simple Python code to write a website
From Wsgiref.simple_server Import Make_serverdef index (): return ' index ' DEF News (): return ' nnnnnnn ' def Runsever (environ,start_response): start_response (status= ' OK ', headers=[(' Content-type ', ' text/html ')]) url=environ[' path_info ' #这是用户访问的url #这里我们访问http://127.0.0.1:8000/ if Url.endswith (' index '): # The function to call is determined by what end of the Web page. return index () elif url.endswith (' News '): return News () else: return ' 404 "This means that when we visit Http://127.0.0.1:8000/index, we return the result of the index function, and the equivalent of doing a website" if __name__ = = ' __main__ ': httpd = Make_server (", 8000,runsever) #相当于启动一个网站, 8000 here means port print (' Server HTTP on port 8008 ... ') Httpd.serve_forever () #一直监听该端口, there is a while loop inside, waiting for others to access
When we do, the browser opens this site, then the relevant data will be returned according to the conditions, the results
Once a request is made, the Runsever function is executed in memory, giving the requester the result,
When we add the code of the ConnectionPool class above to this Web site, you can use Singleton mode to make the access user invoke only the same instance at a time
From wsgiref.simple_server import make_serverimport randomclass connectionpool: __instance = none# default is None def __init __ (self): #链接数据库需要的通行证 self.ip= ' 2.2.2.2 ' self.port= 6379 self.pwd = ' 654321 ' self.username = ' Jay ' #去链接 self.conn_list = [1,2,3,4,5,6] #假设创建了6个链接 @staticmethod def get_instance (): If Connect Ionpool.__instance: #如果实例已经存在, return the created instance directly connectionpool.__instance Else:connectionpo Ol.__instance =connectionpool () #如果是第一次调用, execute the function, instantiate a connection pool return connectionpool.__instance# Assign the object to the static field Def get_ Connection (self): #获取链接 r = Random.randrange (1,6) return Rdef index (): p = connectionpool.get_inst Ance () print (p) # This makes it possible to call the same class every time the user accesses, save memory, then call the ConnectionPool method, for example, choose Link Return ' index ' DEF News (): Return ' nnn NNNN ' def runsever (environ,start_response): Start_response (status= ' OK ', headers=[(' Content-type ', ' text/html ')]) url=environ[' Path_info '] #这is the URL that the user accesses #这里我们访问http://127.0.0.1:8000 if Url.endswith (' index '): #根据网页以什么什么结尾则决定调用的函数 return index () elif u Rl.endswith (' News '): Return News () Else:return ' 404 "" means that when we visit Http://127.0.0.1:8000/index, the index function is returned The results of the implementation, the other equivalent here to engage a website "if __name__ = = ' __main__ ': httpd= make_server (", 8000,runsever) #相当于启动一个网站, 8000 here represents the port print (' Server HTTP on port 8008 ... ') Httpd.serve_forever () #一直监听该端口, there is a while loop inside, waiting for others to access
This way, each time a different person accesses the page, it is called the same class method, can save the server memory
As a result, all the same memory
One of Python design patterns (singleton mode)