Python single-instance mode

Source: Internet
Author: User

Single-Case mode

The singleton pattern (Singleton pattern) is a commonly used software design pattern that is primarily intended to ensure that only one instance of a class exists . A singleton can come in handy when you want the entire system to have only one instance of a class.

For example, the database connection read configuration file, if there are many places need to connect the database during the program running, many places need to create an instance of the database object, which leads to the existence of multiple DB instance objects in the system, which can seriously waste memory resources, in fact, We want only one instance object to exist during a program run.

5 ways to implement a singleton pattern module mode

In fact, thePython module is a natural singleton mode , because when the module is first imported, the file is generated .pyc , and when the second import, the file is loaded directly .pyc without executing the module code again.

Therefore, we just need to define the relevant functions and data in a module, we can get a singleton object. If we really want a singleton class, consider doing this:

mysingleton.py

Class Singleton (object):    def foo (self):        Passsingleton = Singleton ()

Save the above code in a file mysingleton.py , and when you want to use it, import the object from the file directly in the other file, which is the object of the singleton schema

From Demo.my_singleton import Singlesingle.foo ()

  

Using adorners
def Singleton (CLS):    _instance = {}    def _singleton (*args, **kargs):        If CLS not in _instance:            _instance[ CLS] = CLS (*args, **kargs)        return _INSTANCE[CLS]    return _singleton@singletonclass A (object):    def __init__ (Self, x=0):        self.x = Xa1 = A (2) a2 = A (3) print (ID (A1), ID (A2))

  

Using classes
Class Singleton (object):    __instance = None    def __init__ (self, x):        self.x = x        print (x)    @ Classmethod    def My_singleton (CLS, *args, **kwargs):        if not cls.__instance:            cls.__instance = CLS (*args, **kwargs)        return cls.__instance

If you encounter multiple threads The problem will occur

Import Threadingclass Singleton (object): __instance = None def __init__ (self, x): self.x = x Import ti Me Time.sleep (1) # Add interference elements, causing problems with multiple threads @classmethod def my_singleton (CLS, *args, **kwargs): If not cls._    _instance:cls.__instance = CLS (*args, **kwargs) return Cls.__instanceimport threadingdef Task (ARG): obj = Singleton.my_singleton (arg) print (obj) for i in range: T = Threading. Thread (Target=task, args= (i,)) T.start ()-------------------<__main__. Singleton object at 0x00000000025d76d8><__main__. Singleton object at 0x000000000259ff28><__main__. Singleton object at 0x000000001234a208><__main__. Singleton object at 0x000000001234a1d0><__main__. Singleton object at 0x000000001234a438><__main__. Singleton object at 0x000000001234a630><__main__. Singleton object at 0x000000001234a828><__main__. Singleton object at 0x000000001234a978><__main__. Singleton Object at 0x000000001234a748><__main__. Singleton Object at 0x000000001234aac8>

  

WORKAROUND: Locking! Non-locking part concurrent execution, lock part serial execution , speed down, but ensure the data security

Import Threadingclass Singleton (object): __instance = None __instance_lock = Threading. Lock () def __init__ (self, x): self.x = x Import Time Time.sleep (1) # Add interference elements, causing problems with multiple threads @classme                Thod def My_singleton (CLS, *args, **kwargs): With Cls.__instance_lock: # plus lock if not cls.__instance: Cls.__instance = CLS (*args, **kwargs) return Cls.__instanceimport threadingdef Task (arg): obj = Si Ngleton.my_singleton (ARG) print (obj) for i in range: T = Threading. Thread (Target=task, args= (i,)) T.start ()----------------------<__main__. Singleton object at 0x000000000259ff28><__main__. Singleton object at 0x000000000259ff28><__main__. Singleton object at 0x000000000259ff28><__main__. Singleton object at 0x000000000259ff28><__main__. Singleton object at 0x000000000259ff28><__main__. Singleton object at 0x000000000259ff28><__main__. Singleton object at 0x000000000259ff28><__main__. SiNgleton object at 0x000000000259ff28><__main__. Singleton object at 0x000000000259ff28><__main__. Singleton Object at 0x000000000259ff28>

  

Implementation based on the __new__ method (recommended)

When we instantiate an object, we instantiate the object by executing the __new__ method of the class first (we do not write it by default, call object.__new__), and then execute the __init__ method of the class . Initializes the object.

Import Threadingclass Singleton (object): _instance_lock = Threading. Lock () def __init__ (self, x): self.x = x Import Time Time.sleep (1) # Add interference element, cause multi-threading Problem def __ne                W__ (CLS, *args, **kwargs): If not hasattr (CLS, ' _instance '): With Cls._instance_lock: # plus lock Cls._instance = Super (Singleton, CLS). __new__ (CLS) return Cls._instanceimport threadingdef Task (arg): obj = S Ingleton (ARG) print (obj) for i in range: T = Threading. Thread (Target=task, args= (i,)) T.start ()----------------<__main__. Singleton object at 0x000000000257ff60><__main__. Singleton object at 0x000000000257ff60><__main__. Singleton object at 0x000000000257ff60><__main__. Singleton object at 0x000000000257ff60><__main__. Singleton object at 0x000000000257ff60><__main__. Singleton object at 0x000000000257ff60><__main__. Singleton object at 0x000000000257ff60><__main__. Singleton Object at 0x000000000257ff60><__main__. Singleton object at 0x000000000257ff60><__main__. Singleton Object at 0x000000000257ff60>

  

Implementation based on Metaclass method
1. When a class is created by type, the __init__ method of type is automatically executed when the class is created, and the class () executes the type's __call__ method (the __new__ method of the class, __init__ method of the Class) 2. The object is created by the class, and when the object is created, the __init__ of the class Method automatically executes, object () executes the __call__ method of the class

Implementing a single case

Import Threadingclass Singletontype (type): _instance_lock = Threading. Lock () def __init__ (Self,class_name,class_bases,class_dic): Super (Singletontype, self). __init__ (Class_name,class _bases,class_dic) def __call__ (CLS, *args, **kwargs): If not hasattr (CLS, ' _instance '): With Cls._ins Tance_lock: # plus lock cls._instance = Super (Singletontype, CLS). __call__ (*args, **kwargs) return cls._in     Stanceclass My_singlton (metaclass=singletontype): def __init__ (self,x): self.x = ximport threadingdef Task (ARG): obj = My_singlton (arg) print (obj) for i in range: T = Threading. Thread (Target=task, args= (i,)) T.start ()--------------------------<__main__.my_singlton object at 0x00000000025cff60><__main__.my_singlton object at 0x00000000025cff60><__main__.my_singlton object at 0x00000000025cff60><__main__.my_singlton object at 0x00000000025cff60><__main__.my_singlton object at 0x00000000025cff60><__maIn__.my_singlton object at 0x00000000025cff60><__main__.my_singlton object at 0x00000000025cff60><__main __.my_singlton object at 0x00000000025cff60><__main__.my_singlton object at 0x00000000025cff60><__main__ . My_singlton object at 0x00000000025cff60>

  

Singleton mode use

 

Import Threadingclass Singletondb (object): _instance_lock = Threading.            Lock () def __init__ (self,host= ' 127.0.0.1 ', port=3306, user= ' root ', password= ' root ', Database= ' TestDB ', charset= ' UTF8 '): self.host = host Self.port = Port Self.passwo RD = Password Self.user = user Self.database = Database Self.charset = CharSet def __new__ (CLS, *a                RGS, **kwargs): If not hasattr (singletondb, "_instance"): With Singletondb._instance_lock: If not hasattr (singletondb, "_instance"): Singletondb._instance = object.__new__ (CLS, *args, **kwargs return singletondb._instance def Connect (self): print (' Connect db ') DB1 = singletondb () DB2 = SINGLETONDB () print (DB1,DB2) db1.connect () db2.connect ()----------------<__main__. Singletondb object at 0x00000000025e76d8> <__main__. Singletondb object at 0x00000000025e76d8>connect Dbconnect db

  

Python single-instance mode

Related Article

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.