A singleton pattern of design patterns

Source: Internet
Author: User

Singleton , as the name implies, is a single instance

1. Advantages of single-case mode
    • The singleton pattern produces only one object, which reduces the overhead, and when an object's generation requires more resources, such as reading a configuration file and generating other dependent objects, it can directly produce a singleton object when its application is started. Then the permanent presence of memory in the way to solve.
    • The singleton mode allows the system to set the global access point. Optimizes access to shared resources. For example, you can design a singleton class that is responsible for mapping all the data tables.

2. Single-Instance realization method

Let's look at a common scenario:

This common method will be the memory consumption under the large traffic!

Each request arrives, it is necessary to create an instance in memory, and then execute the specified method through the instance.

So the problem comes ... If the concurrency is large, there will be a lot of the object that is functionally identical.

#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server Import make_serverclass DBHelper (object): Def __init__ (     Self): Self.hostname = ' 1.1.1.1 ' self.port = 3306 Self.password = ' pwd ' self.username = ' root '    def fetch (self): # Connect Database # Stitch SQL statement # operation return ' fetch ' def create (self): # Connect Database # Stitching SQL statements # operation return ' Create ' def remove (self): # Connect Database # Stitching SQL statement # operation return ' remove ' def modify (sel        f): # Connect to Database # Stitch SQL statement # operation return ' Modify ' class Handler (object): Def index (self): # Create Object db = DBHelper () Print ID (db) db.fetch () return ' index ' DEF News: Return ' news ' Def Run Server (environ, start_response): Start_response (' $ OK ', [(' Content-type ', ' text/html ')]) url = environ[' Path_info ' ] Temp = url.split ('/') [1] obj = Handler () is_exist = hasattr (obj, temp) If Is_exist:func = GetAttr (ob J, temp) ret = func () return ret Else:return ' 404 Not Found ' if __name__ = = ' __main__ ': httpd = Make_server (", 8001, RunS    erver) print "Serving HTTP on port 8001 ..." Httpd.serve_forever ()

The above example is the operation of the database. When the amount of operation is very high, it generates a lot of memory consumption, because each request creates an instance

For these functions the same object can be created in memory only one, need to go to call, is also excellent!!!

Singleton mode is used to ensure that only one instance exists in memory!!! @classmethod or static methods @staticmethod by class methods can be implemented  

Principle: Through the object-oriented characteristics, constructs a singleton pattern:

  • The class method @classmethod (cls= current class ) trigger is a class that is called directly with a class , with only one parameter CLS c2> to static methods, there can be only one parameter, the parameter will automatically pass the current class when the value is passed. In the case of Singleton mode.
  • a static method belongs to a class @staticmethod Trigger class, which does not require arguments () and can have multiple arguments class Plus static method = a function. Creating an object gives you access to the method, as if you were creating a function. A static method is useful if all the programs require object-oriented instead of functions.

Why do you have a class method and a static method?

because without both methods, the object is created at the time of invocation to invoke the method. Both of these methods can be called directly from the class, saving memory.  
#!/usr/bin/env python#Coding:utf-8 fromWsgiref.simple_serverImportMake_server############ Singleton class definition ###########classDBHelper (object):__instance = None        #Create a private static field to hold an instance field that is always present in memory    def __init__(self): Self.hostname='1.1.1.1'Self.port= 3306Self.password='pwd'Self.username='Root'@staticmethod def Singleton (): If Dbhelper.__instance:return dbhelper.__instance Else : Dbhelper.__instance = DBHelper () return dbhelper.__instance    deffetch (self):#connecting to a database    #Splicing SQL statements    #Operation        Pass    defCreate (self):#connecting to a database    #Splicing SQL statements    #Operation        Pass    defRemove (self):#connecting to a database    #Splicing SQL statements    #Operation        Pass    defModify (self):#connecting to a database    #Splicing SQL statements    #Operation        PassclassHandler (object):defindex (self): obj=Dbhelper.singleton ()   #calling a static method directly through a class        PrintID (obj) obj.create ()return 'Index'    defNews (self):return 'News'defrunserver (environ, start_response): Start_response ('OK', [('Content-type','text/html')]) URL= environ['Path_info'] Temp= Url.split ('/') [1] obj=Handler () is_exist=hasattr (obj, temp)ifIs_exist:func=getattr (obj, temp) ret=func ()returnretElse:        return '404 Not Found'if __name__=='__main__': httpd= Make_server ("', 8001, Runserver)Print "serving HTTP on port 8001 ..."Httpd.serve_forever ()

  

A singleton pattern of design patterns

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.