Common three ways to implement a singleton pattern in Python

Source: Internet
Author: User
Singleton mode is a kind of 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.

The main points of the singleton pattern are three; one is that a class can have only one instance, and the other is that it must create this instance on its own, and thirdly, it must provide this instance to the whole system on its own. In Python, the singleton pattern is implemented in the following ways.

method One , implement the __new__ method, and then bind an instance of the class to the class variable _instance, if Cls._instance is None, then the class has not been instantiated, new an instance of the class, and returns, if Cls._ Instance not for none, return directly to _instance, the code is as follows:

Class Singleton (object):   def __new__ (CLS, *args, **kwargs):    If not hasattr (CLS, ' _instance '):      orig = Super ( Singleton, CLS)      cls._instance = orig.__new__ (CLS, *args, **kwargs)    return cls._instance class MyClass ( Singleton):  a = 1 one = MyClass ()-MyClass () #one和two完全相同, can be detected with ID (), = =, is detection print ID (one)  # 29097904print ID (TW o)  # 29097904print One = = both # Trueprint one is both  # True

method Two , is essentially an upgraded version of method one, using __metaclass__ (meta-Class) of the advanced Python usage, the code is as follows:

Class Singleton2 (Type):   def __init__ (CLS, name, bases, Dict):    super (Singleton2, CLS). __INIT__ (name, bases, dict)    cls._instance = None   def __call__ (CLS, *args, **kwargs):    if Cls._instance is None:      cls._instance = Super (Singleton2, CLS). __call__ (*args, **kwargs)    return Cls._instance class MyClass2 (object):  __metaclass_ _ = Singleton2  A = 1 one = MyClass2 () b = MyClass2 () Print ID (one)  # 31495472print ID (one) #  31495472print o NE = = one  # trueprint one is  the


method Three , using the Python decorator (decorator) to implement a singleton mode, which is a more pythonic method; The code of simple interest class itself is not a singleton, the pass decorator makes it a singleton, the code is as follows:

Def Singleton (CLS, *args, **kwargs):  instances = {}  def _singleton ():    If CLS not in instances:      instances [CLS] = CLS (*args, **kwargs)    return INSTANCES[CLS]  return _singleton @singletonclass MyClass3 (object):  a = 1 one = MYCLASS3 () MYCLASS3 () Print ID (one)  # 29660784print ID (one)  # 29660784print one =  # Trueprin T one is both  # True
  • 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.