There are three common methods to implement the singleton mode in Python and three methods for python.

Source: Internet
Author: User

There are three common methods to implement the singleton mode in Python and three methods for python.

The Singleton mode is a common software design mode. Its core structure only contains a special class called Singleton class. The Singleton mode ensures that there is only one instance in a class in the system and the instance is easy to access, so as to conveniently control the number of instances and save system resources. If you want to have only one class object in the system, the singleton mode is the best solution.

The Singleton mode has three key points: one is that a class can only have one instance; the other is that it must create the instance on its own; and the third is that it must provide the instance to the entire system on its own. In Python, the singleton mode has the following implementation methods.

Method 1, Implement the _ new _ method, and then bind an instance of the class to the class Variable _ instance; If cls. if _ instance is None, it indicates that the class has not been instantiated. A new instance of this class is returned. If cls. if the value of _ instance is not None, _ instance is directly returned. 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 () two = MyClass () # one and two are identical. You can use id (), =, is check print id (one) #29097904 print id (two) #29097904 print one = two # Trueprint one is two # True

Method 2In essence, it is an upgraded version of method 1. Use the advanced python usage of _ metaclass _ (Meta class). The specific 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()two = MyClass2() print id(one)  # 31495472print id(two)  # 31495472print one == two  # Trueprint one is two  # True


Method 3The Python decorator is used to implement the singleton mode, which is a more Pythonic method. The code of the singleton class itself is not Singleton, And the modifier makes it 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()two = MyClass3() print id(one)  # 29660784print id(two)  # 29660784print one == two  # Trueprint one is two  # 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.