Python single-instance mode

Source: Internet
Author: User

One, what is a singleton mode

Singleton mode: guarantees that a class has only one instance and provides a global access point to access him.

A way to implement only one instance of a class:

1. Let a global variable make an object accessible, but he cannot prevent external instantiation of multiple objects.

2, let the class itself save his only instance, this class can guarantee that no other instances can be created.

Multi-threaded Singleton mode: locking-double lock

A hungry man Singleton class: instantiates itself (statically initialized) when the class is loaded. The advantage is that it avoids the security problem of multi-threaded access, and the disadvantage is that it occupies the system resources beforehand.

Lazy Singleton class: The first time you are referenced, you instantiate yourself. Avoid using system resources at the start, but have multiple thread access security issues.

Second, how to achieve a single case mode

The implementation of the singleton model I summed up three ways:

1, file Import, when the file is imported as a module, only executed once, so a class, there is only one instance, and therefore can be a singleton mode.

When the import test# module is imported, the test is automatically executed to create a unique instance object.

2, class method, create a singleton mode.

Class Foo (object): _instance = Nonedef __init__ (self):p ass@classmethoddef get_instance (CLS): If Cls._instance:return Cls._instanceelse:obj = CLS () cls._instance = Objreturn objobj1 = foo.get_instance () Obj2 = Foo.get_instance () # with ID (), = =, I s detection to see if it is the same object. Print (ID (obj1))            # 39514520print (ID (obj2))            # 39514520print (obj1 = = obj2)    # trueprint (Obj1 is obj2)       # True

3, __new__ method, is better than the method two, the use of the traditional example method, that is, the class name + (). Avoid tedious document descriptions.

Class Foo (object):    _instance = None    def __init__ (self):        pass    def __new__ (CLS, *args, **kwargs):        If cls._instance:            return cls._instance        else:            obj = object.__new__ (cls,*args,**kwargs)            cls._ Instance = obj            return obj# is also a traditional instantiation object method. obj1 = foo () obj2 = foo () # with ID (), = =, is detected to see if it is the same object. Print (ID (obj1))                 # 39514520print (ID (obj2))                 # 39514520   print (obj1 = = obj2)        # trueprint (Obj1 is Obj2 )           # True

Looking forward to updating ...

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.