Python single-instance mode

Source: Internet
Author: User

1. Introduction of single-case mode

Singleton mode, also known as the list mode, is a common software design pattern. When you apply this pattern, the class of the Singleton object must guarantee that only one instance exists. Many times the entire system only needs to have a global object, which helps us coordinate the overall behavior of the system. --Above from Wikipedia

In terms of definition, this can be a useful design pattern to avoid conflicts, which is equivalent to having all of the same resources transferred to a resource agent. So how do you implement this pattern in Python?

#!/usr/bin/env python# _*_ coding:utf-8 _*_# Author:enzhi.wangclass Foo:    ' singleton mode '    instance = None    def __init_ _ (Self,name):        self.name = name    @classmethod    def get_instance (CLS):        # CLS class name        if cls.instance:            return cls.instance        else:            obj = CLS ("Alex")            cls.instance = obj            return objobj1 = foo.get_ Instance () print (obj1) obj2 = Foo.get_instance () print (OBJ2)

The result of the above code is:

C:\Python3.5\python.exe c:/users/root/pycharmprojects/s14/Object-oriented/ singleton mode. PY<__main__. Foo object at 0x0000000000a92588><__main__. Foo Object at 0x0000000000a92588>

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.