An example of pymysql application of singleton pattern

Source: Internet
Author: User

What is a single case? A brief introduction to the following: a single case is what a ghost!!!! Single-instance mode meaning "
 Singleton mode is a common software design pattern. In its core structure, it contains only a special class called a singleton class. The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system. 
Use singleton mode motivation, reason
for some classes in the system, only one instance is important, for example, multiple print tasks can exist in a system, but only one task is working; a system can have only one window manager or file system ; A system can have only one timing tool or ID (ordinal) generator. You can only open one task Manager in Windows. If you do not use the mechanism to unique window objects, will pop up more than one window, if these windows display exactly the same content, it is a duplicate object, wasting memory resources, if these windows display inconsistent content, it means that in a moment the system has multiple states, and the actual discrepancy, but also to the user misunderstanding, I don't know which one is the real state. Therefore, it is sometimes important to ensure that an object in the system is unique, that only one instance of a class is available. How does the
guarantee that there is only one instance of a class and that the instance is easily accessible? Defining a global variable ensures that an object can be accessed at any time, but it does not prevent us from instantiating multiple objects. A better solution is to have the class itself responsible for preserving its only instance. This class guarantees that no other instance is created, and it can provide a way to access the instance. This is the pattern motive of the singleton pattern.

Singleton mode advantages and disadvantages

Advantages
One, instance control

Singleton mode prevents other objects from instantiating copies of their own singleton objects, ensuring that all objects have access to unique instances.

Second, flexibility

because the class controls the instantiation process, classes can flexibly change the instantiation process.

"Disadvantage"
one, overhead
Although the number is small, but if each time the object requests the reference to check whether there is an instance of the class, there will still be some overhead. This problem can be resolved by using static initialization.

Second, possible development confusion
when using singleton objects, especially those defined in a class library, developers must remember that they cannot instantiate objects using the New keyword. Because library source code may not be accessible, application developers may unexpectedly find themselves unable to instantiate this class directly.

Third, object lifetime

The problem of deleting a single object cannot be resolved. In a language that provides memory management, such as a. NET framework-based language, only a singleton class can cause an instance to be deallocated because it contains a private reference to the instance. In some languages (such as C + +), other classes can delete object instances, but this can result in a floating reference in a singleton class

Simple comprehension of the singleton pattern

1 Singleton mode allows only one object to be created, thus saving memory and speeding up object access, so objects need to be used in a common situation, such as multiple modules connecting objects using the same data source, etc.


2 The disadvantage of the singleton is not suitable for changing objects, if the same type of objects are always to be changed in different use case scenarios, the singleton will cause data errors, cannot save each other's state.
Using a singleton mode, it is used in a state where its merits are applied

Don't be naïve to think I wrote it! In fact, I am a copy of the concept! haha haha ....

Now that you understand the singleton pattern, here's how to use singleton mode

In Python, we can implement a singleton pattern in a variety of ways:

-Using modules

-Using __new__

-Using adorners

-Use meta-class (Metaclass)

Using modules

In fact, the Python module is a natural singleton mode, because when the module is first imported, the. pyc file is generated, and when the second import, the. pyc file is loaded directly, and the module code is not executed again. So we just need to define the relevant functions and data in a module, we can get a singleton object.

# Mysingle.pyclass Mysingle:
def foo (self):
Pass

Sinleton = Mysingle ()
Save the above code in the file mysingle.py, and then use:
From Mysingle import Sinleton
Singleton.foo ()

Using __new__

In order for a class to appear only one instance, we can use __new__ to control the creation of the instance, with the following code:

class Singleton(object): def __new__(cls): # The key is this, every time we instantiate, we'll just return the same instance object. if not hasattr(cls, ' instance '): cls. Instance = Super(Singleton, cls). __new__(cls) return cls. Instance obj1 = Singleton() obj2 = Singleton() obj1. ATTR1 = ' value1 ' print obj1. Attr1, obj2. ATTR1 Print obj1 is obj2 Output Result:value1 value1

Using adorners:

We know that adorners can dynamically modify the functionality of a class or function. Here, we can also use adorners to decorate a class so that it can produce only one instance:

Def Singleton (CLS):    instances = {}    def getinstance (*args,**kwargs):        If CLS not in instances:            instances [CLS] = CLS (*args,**kwargs)        return INSTANCES[CLS]    return getinstance@singletonclass MyClass:    a = 1C1 = MyClass () C2 = MyClass () print (C1 = = C2) # True


Above, we define an adorner singleton , which returns an intrinsic function getinstance ,
The function will determine if a class is in the dictionary instances , and if it does not, it will be cls stored as key as cls(*args, **kw) value instances ,
Otherwise, return directly instances[cls] .

Using Metaclass (Meta Class)

A meta-class can control the process of creating a class, and it does three things mainly:

-Block creation of classes

-Modify the definition of a class

-Returns the modified class

To implement a singleton pattern using a meta-class:

Class Singleton2 (Type):    def __init__ (self, *args, **kwargs):        self.__instance = None        super (Singleton2, Self). __init__ (*args, **kwargs)    def __call__ (self, *args, **kwargs):        if Self.__instance is None:            self.__ Instance = Super (singleton2,self). __call__ (*args, **kwargs)        return Self.__instanceclass Foo (object):    __ metaclass__ = Singleton2 #在代码执行到这里的时候, __new__ methods and __init__ methods in the meta-class are actually executed, not when Foo is instantiated. and is executed only once. foo1 = foo () Foo2 = foo () print (foo.__dict__)  #_Singleton__instance ': <__main__. Foo object at 0x100c52f10> has a private property to hold the property without polluting the Foo class (it is still polluting, but cannot be accessed directly through the __instance property) print (Foo1 is Foo2)  # True

Class based on the Pymysql operation (Singleton mode)

From conf import settingimport pymysqlclass mysql:__instance = Nonedef __init__ (self): Self.conn = Pymysql.connect (host= Setting.host,user=setting.user,password=setting.password,database=setting.database,charset=setting.charset, Autocommit=setting.autocommit) Self.cursor = Self.conn.cursor (cursor=pymysql.cursors.dictcursor) def close_db (self) : Self.conn.close () def select (Self, SQL, Args=none): Self.cursor.execute (sql, args) rs = Self.cursor.fetchall () return Rsdef Execute (Self, SQL, args): Try:self.cursor.execute (SQL, args) Affected = self.cursor.rowcount# Self.conn.commit () Except Baseexception as E:print (e) return Affected@classmethoddef Singleton (CLS): if not cls.__instance:cls.__instance = CLS () return cls.__instance

  

The blog continues to update, the small partners are cautious into ...

Author:rianley Cheng

Author Email: [Email protected]

Author qq:2855132411

An example of pymysql application of singleton pattern

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.