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