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