First, the significance of singleton pattern

Singleton here is only one instance (as in the instance of object-oriented, created an object can also create an instance), only one instance of program design, first of all, we can know the when it is not suitable for using the singleton pattern, such as we need to use classes to create multiple objects at the same time, The singleton pattern cannot be used when each object encapsulates different data, as in the following example

class Person: def __init__(self,name,age): Self. name = name self.age = age mingming = Person(' mingyue ',19) mingming = Person(' mingyue ',30) minggri = Person(' mingyue ',20)Copy the code

So when is it appropriate to use the singleton pattern, if each object encapsulates the same data, but needs to create multiple objects, and the two instances are all the same function, so we can use one instance to do this, here we can use the singleton pattern, as follows

class Person:
    def __init__(self):
        self.name = '123123'
        self.age = '20'

    def f1(self):
        pass

    def f2(self):
        pass

mingming = Person()
mingming.f1()

mingyue = Person()
mingyue.f1()Copy the code

The reason for using the singleton mode is to reduce the memory usage by using only one instance to complete the functions of multiple same instances without creating multiple objects when the encapsulated data is the same and each instance can execute the same method.

2. Application scenarios of singleton pattern

  • Objects that require frequent creation and destruction;
  • Objects that take too much time or resources to create, but are often used.
  • Tool class object;
  • Objects that frequently access databases or files.

Advantages and disadvantages of singleton pattern

advantages

Only one object of this class exists in the system memory, saving system resources. For some objects that need to be created and destroyed frequently, the singleton mode can improve system performance.

Because the singleton pattern has only one instance in memory, memory overhead is reduced. The singleton mode can avoid multiple resource usage. For example, when a file is written, only one instance exists in the memory. Therefore, simultaneous write operations on the same resource file are avoided. Singleton mode allows the system to set global access points, optimize and share resource access. When using singleton mode, how to prevent the simultaneous creation of multiple threads is considered more.

When an object of this class is created in more than one place, the internal method is called multiple times, but you want only one object to operate on the method, or you don’t want multiple places to call the method at the same time, and you want to keep the method single, use simple profit mode

disadvantages

With the singleton pattern, scaling is difficult, and there is almost no other way to do it than by modifying the code.

Fourth, singleton pattern code writing

Then we simulate a database connection pool to implement the singleton pattern First we introduce the database connection pool We through the procedures for the operation of the database, each time need to connect to the database, but connect to the database will consume more time, so we can be in the memory of our host maintain a database connection pool, In this connection pool, there are several connections already connected to the database. When we want to connect to the database, we can directly take a connection from the connection pool, saving the connection time.

Non-singleton pattern

import random class SqlConnectionPool: __instance = None def __init__(self): Self. IP = "127.0.0.1" self.port = 3306 self. PWD = '123456' self.username = 'alexsel ,2,3,4,5,6,7,8,9,10 [1] def get_connection (self) : R = random. Randrange (1,11) return r Obj = SqlConnectionPool() print(obj) obj1 = SqlConnectionPool() print(obj1) obj2 = SqlConnectionPool() Print (obj2)  <__main__.SqlConnectionPool instance at 0x0000000002630788> <__main__.SqlConnectionPool instance at 0x0000000002630888>  <__main__.SqlConnectionPool instance at 0x00000000026308C8>Copy the code

In the non-singleton mode, the result of the memory output is different each time. Here is the singleton mode.

import random class SqlConnectionPool: __instance = None def __init__(self): Self. IP = "127.0.0.1" self.port = 3306 self. PWD = '123456' self.username = 'alexsel Def get_instance(): if sqlConnectionPool.__instance: return SqlConnectionPool.__instance else: # create an object SqlConnectionPool.__instance = SqlConnectionPool() return SqlConnectionPool.__instance # Singleton key code parsing # When this static method is called for the first time, check that __instacne is None, so do else, then create an object in the else that assigns __instance to the static field, and return the static field. # When this static method is called for the second time, Def get_connection(self) def get_connection(self) def get_connection(self) def get_connection(self): R = random. Randrange (1,11) return r Sqlconnectionpool.get_instance () print(obj) obj1 = SQLConnectionPool.get_instance () print(obj1) obj2 = Sqlconnectionpool.get_instance () print(obj2)  <__main__.SqlConnectionPool instance at 0x000000000260C808> <__main__.SqlConnectionPool instance at 0x000000000260C808>  <__main__.SqlConnectionPool instance at 0x000000000260C808>Copy the code

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