Singleton mode, Mode

Source: Internet
Author: User

Singleton mode, Mode

 

Singleton ModeIs a common software design pattern, which aims to ensure that a class only has one instance.

Under what circumstances can the singleton mode be used:
1. When each instance occupies resources and instance initialization affects performance, you can consider using the singleton mode. The advantage of this mode is that only one instance occupies resources, and only needs to be initialized once;

2. When synchronization is required, you can use an instance for synchronization control, such as the control of a shared file (such as a log file) and the synchronization control of the counter,

In this case, there is only one instance, so you don't have to worry about synchronization.

In python, we can use four methods to implement the singleton mode:
1. Use modules

2. Use _ new __

3. decorator

4. Use metadata

I. Use modules

  The python module is a natural Singleton mode,When the module is imported for the first time, the. pyc file is generated. When the module is imported again, the. pyc file is directly loaded,

Instead of running the code in the module. Therefore, you only need to write the relevant functions or data in a module, You can import the module

Obtain a singleton object.

# single_mode.pyclass SingleMode(object):    def foo(self):        pass single_obj = SingleMode()

 

Save the above Code in the single_mode.py file, and then use:

from mysingleton import single_mode single_mode.foo()

Ii. Use _ new __:

We can use__new__To control the instance creation process, the Code is as follows:

class SingleMode(object):    _instance = None    def __new__(cls, *args, **kw):        if not cls._instance:            cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)          return cls._instance   class MyClass(SingleMode):      a = 1

 

In the above Code, we set the class instance and a class variable_instanceAssociated, ifcls._instanceIf this parameter is set to None, an instance is created. Otherwise, an instance is returned.cls._instance.

 

3. decorator

  You can use the decorator to decorate a class so that it can generate only one instance. The Code is as follows:

from functools import wraps def singlemode(cls):    instances = {}    @wraps(cls)    def getinstance(*args, **kw):        if cls not in instances:            instances[cls] = cls(*args, **kw)        return instances[cls]    return getinstance @singlemodeclass MyClass(object):    a = 1

In the above, we define a decoratorsinglemode, It returns an internal functiongetinstanceTo determine whether a class is in the dictionary.instancesMedium,

If it does not existclsAs key,cls(*args, **kw)Save as valueinstances. Otherwise, return directly.instances[cls].

4. Use metaclass

Metaclass allows you to control the creation process of a class. It mainly involves three tasks:

  • Create an interception class
  • Modify the definition of a class
  • Returns the modified class.

The code for using the Meta class to implement the singleton mode is as follows:

class Singleton(type):    _instances = {}    def __call__(cls, *args, **kwargs):        if cls not in cls._instances:            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)        return cls._instances[cls]class MyClass(metaclass=Singleton):   pass

 

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.