Python Learning: 19.Python design mode-Singleton mode

Source: Internet
Author: User

The significance of the existence of singleton pattern

The singleton here is only one instance (where an instance is created as an object-oriented object or an instance is created), and is programmed with just one instance, first we can see when it is not appropriate to use a singleton pattern, such as when we need to use a class to create multiple objects at the same time, And when different data is encapsulated in each object, you cannot use singleton mode, as in the following example

class Person :     def __init__ (self,name,age):         = name          = age = person (' plainly ', + = person (          ' the moon ',the person (' tomorrow ', 20)

So when is the right time to use singleton mode, if each object encapsulates the same data, but need to create multiple objects, and all of the two instances of the same function, so we can use an instance to complete, here we can use the singleton mode, as follows

 class   person:  def  __init__   =   123123     Self.age  = "  20    def   F1 (self):  pass  def   F2 (self):  pass  mingming  = person () Mingming.f1 () Mingyue  = person () Mingyue.f1 ()  

Why use singleton mode, in order to encapsulate the data in the same case, and each instance can be executed in the same way, do not have to create multiple objects, only one instance to complete the functions of multiple identical instances, in this way reduce the use of memory.

Second, the scenario of single-case mode application

    • Objects that need to be created and destroyed frequently;
    • Objects that are too time-consuming or resource-intensive, but often used when creating objects;
    • Tool class object;
    • An object that frequently accesses a database or file.

Advantages and disadvantages of the single-case model

Advantages

In system memory, there is only one object in the class, saving system resources, and using singleton mode can improve system performance for some objects that need to be destroyed frequently.

Because Singleton mode has only one instance in memory, the memory overhead is reduced.
Singleton mode avoids multiple uses of resources, such as when a file is written, because only one instance exists in memory, avoiding simultaneous write operations to the same resource file.
The singleton mode allows the system to set global access points, optimize and share resource access.
When using the singleton mode, it is more about how to prevent multiple threads from being created in multi-threaded situations.

When the object of this class is created in more than one place, the internal method is called multiple times, but hopefully as long as an object operates this method, or does not want to call this method in multiple places at the same time, it needs to maintain a single property of this method, using simple interest mode

Disadvantages

With the singleton pattern, it is difficult to extend, except that there is basically no second way to implement the modification code.

Four, the single-case pattern code writing

Next we'll simulate a database connection pool to implement a singleton pattern
Let's start by introducing the database connection pool
We use the program to operate the database, each time we need to connect to the database, but the connection to the database needs to consume more time, so we can in our host's memory to maintain a database connection pool, in this connection pool has a number of connected database connection, We want to connect to the database directly to the connection pool to remove a connection, eliminating the connection time.

Non-singleton mode

ImportRandomclassSqlconnectionpool:__instance=Nonedef __init__(self): Self.ip="127.0.0.1"Self.port= 3306self.pwd='123456'Self.username='Alexsel'        #to connectSelf.conn_list = [1,2,3,4,5,6,7,8,9,10]    defget_connection (self):#Get ConnectionsR = Random.randrange (1,11)        returnR#we create multiple objects with the same memory address, which means we get the same object.obj =Sqlconnectionpool ()Print(obj) obj1=Sqlconnectionpool ()Print(obj1) obj2=Sqlconnectionpool ()Print(OBJ2) output results:<__main__. Sqlconnectionpool instance at 0x0000000002630788><__main__. Sqlconnectionpool instance at 0x0000000002630888><__main__. Sqlconnectionpool instance at 0x00000000026308c8>

Non-singleton mode each time the results of memory output are different, the following is a singleton mode.

ImportRandomclassSqlconnectionpool:__instance=Nonedef __init__(self): Self.ip="127.0.0.1"Self.port= 3306self.pwd='123456'Self.username='Alexsel'        #to connectSelf.conn_list = [1,2,3,4,5,6,7,8,9,10] @staticmethod#static methods are called by the class.    defget_instance ():ifSqlconnectionpool.__instance:            returnSqlconnectionpool.__instance        Else:            #creates an object and assigns the object to a static field __instanceSqlconnectionpool.__instance=Sqlconnectionpool ()returnSqlconnectionpool.__instance    #analysis of key code of single case mode    #when this static method is called for the first time, it is determined that the value of __instacne is none so do else, then create an object in else to assign to the static field __instance, and return this static field    #The second time this static method is called, judge the value of __instance is true, so directly return this static field, and this static field contains the first created object, so at a later call this method    #only the object that was created for the first time is called, and this is the singleton mode    defget_connection (self):#Get ConnectionsR = Random.randrange (1,11)        returnR#we create multiple objects with the same memory address, which means we get the same object.obj =sqlconnectionpool.get_instance ()Print(obj) obj1=sqlconnectionpool.get_instance ()Print(obj1) obj2=sqlconnectionpool.get_instance ()Print(OBJ2) output results:<__main__. Sqlconnectionpool instance at 0x000000000260c808><__main__. Sqlconnectionpool instance at 0x000000000260c808><__main__. Sqlconnectionpool instance at 0x000000000260c808>

The above is a singleton pattern implemented based on classes, using static fields and static methods.

Python Learning: 19.Python design mode-Singleton mode

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.