Python implementation Singleton mode

Source: Internet
Author: User

Singleton mode 1. What are single cases?

Make sure that there is only one instance of a class, and instantiate it yourself and provide this instance to the entire system, which is called a singleton class, and the singleton pattern is an object-creation pattern.
So what is the use of the singleton model? As an example of a common singleton pattern, we usually use a computer that has a recycle Bin, in the entire operating system, the Recycle Bin can only have one instance, the entire system uses this unique instance, and the Recycle Bin provides its own instance, so the Recycle Bin is a singleton mode application.

2. Create a singleton-guaranteed only 1 objects
class Singleton(object):    __instance = None    def __new__(cls, name, age):        # 如果类属性__instance的值为None,那么就创建一个对象        if not cls.__instance:            cls.__instance = object.__new__(cls)        # 如果已经有实例存在,直接返回        return cls.__instancea = Singleton("Zhangsan", 18)b = Singleton("lisi", 20)print(id(a))print(id(b))a.age = 30   # 给a指向的对象添加一个属性print(b.age)  # 获取b指向的对象的age属性

Operation Result:

2946414454432294641445443230
3. Create a singleton and perform only 1 timesInitMethod
class Singleton(object):    __instance = None    __first_init = False    def __new__(cls, name, age):        if not cls.__instance:            cls.__instance = object.__new__(cls)        return cls.__instance    def __init__(self, name, age):        if not self.__first_init:            self.name = name            self.age = age            Singleton.__first_init = Truea = Singleton("Zhangsan", 18)b = Singleton("lisi", 20)print(id(a))print(id(b))print(a.name, a.age)print(b.name, b.age)a.age = 50print(b.age)

Operation Result:

22066402853442206640285344Zhangsan 18Zhangsan 1850

Python implementation Singleton 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.