Python single-instance mode

Source: Internet
Author: User

Method One

Python code
  1. Import threading
  2. Class Singleton (object):
  3. __instance = None
  4. __lock = Threading. Lock () # used to synchronize code
  5. def __init__ (self):
  6. "Disable the __init__ method"
  7. @staticmethod
  8. def getinstance ():
  9. if not singleton.__instance:
  10. Singleton.__lock.acquire ()
  11. if not singleton.__instance:
  12. Singleton.__instance = object.__new__ (Singleton)
  13. object.__init__ (singleton.__instance)
  14. Singleton.__lock.release ()
  15. return singleton.__instance

1. Disable the __init__ method, and you cannot create objects directly.

2.__instance, privatization of single-instance objects.

[email protected], static method, directly called through the class name.

4.__lock, code lock.

5. Inherit the object class, create a singleton object by calling the __new__ method of object, and then call the __init__ method of object to complete the initialization.

6. Double check lock, both to achieve thread safety and performance is not greatly affected.

Method Two: Use decorator

Python code
  1. #encoding =utf-8
  2. Def Singleton (CLS):
  3. instances = {}
  4. def getinstance ():
  5. if cls not in instances:
  6. instances[CLS] = cls ()
  7. return instances[CLS]
  8. return getinstance
  9. @singleton
  10. Class Singletonclass:
  11. Pass
  12. if __name__ = = ' __main__ ':
  13. s = Singletonclass ()
  14. S2 = Singletonclass ()
  15. Print S
  16. Print S2

You should also add thread safety

Attached: Performance no method one high

Python code
  1. Import threading
  2. Class Sing (object):
  3. def __init__ ():
  4. "Disable the __init__ method"
  5. __inst = None # make it so-called private
  6. __lock = Threading. Lock () # used to synchronize code
  7. @staticmethod
  8. def getinst ():
  9. Sing.__lock.acquire ()
  10. if not sing.__inst:
  11. Sing.__inst = object.__new__ (Sing)
  12. object.__init__ (Sing.__inst)
  13. Sing.__lock.release ()
  14. return Sing.__inst

Python single-instance 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.