Python implementation of a single-instance implementation method.
The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system.
#Coding:utf-8" "implementation of a single example implementation of Adorners" "defSingleton (CLS, *args, * *Kwargs): Instance= {} def_singleton ():ifCls not inchInstance:instance[cls]= CLS (*args, * *Kwargs)returninstancereturn_singleton@singletondefMyClass (): a= 1def __init__(Self, x=0): self.x=xa=MyClass () b=MyClass () a.a= 3PrintB.A#3A isb#True
The so-called Singleton is a class that can only create one instantiation.
- A class can have only one instance
- It must create this instance on its own
- This instance must be provided to the entire system on its own
Python single case