Python design pattern

Source: Internet
Author: User
I. Singleton mode

Singleton mode (singleton pattern) is one of the simplest design patterns. This type of design pattern belongs to the Create pattern, which provides an optimal way to create an object. This pattern involves a single class that is responsible for creating its own objects, and the colleague ensures that only a single object is created, and that the class provides a way to access its only object, which can be accessed directly without instantiating the object of that class. Singleton mode is a class that can only create one instantiated object!

Attention:

  • A singleton class can have only one instance
  • The Singleton class must create its own unique instance
  • The Singleton class must provide this instance to all other objects

Class Foo:    instance = None    def __init__ (self, name):        self.name = name    @classmethod    def get_ Instance (CLS):        if cls.instance:            return cls.instance        else:            obj = CLS ("AAA")            cls.instance = obj            return objobj1 = Foo.get_instance () print (obj1) obj2 = Foo.get_instance () print (OBJ2) # output <__main__. Foo object at 0x1007f9550><__main__. Foo Object at 0x1007f9550>

  

Not to be continued

Python design pattern

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.