Single-Case mode
Multiple instantiation results point to the same instance
Single-instance mode implementation method
Way One:
1 ImportSettings2 3 classMySQL:4 __instance=None5 6 def __init__(self, IP, port):7Self.ip =IP8Self.port =Port9 Ten @classmethod One deffrom_conf (CLS): A ifCls.__instance isNone: -Cls.__instance=CLS (Settings. Ip,settings. PORT) - returnCls.__instance the -Obj1 =mysql.from_conf () -Obj2 =mysql.from_conf () -Obj3 =mysql.from_conf () + Print(OBJ1) - Print(OBJ2) + Print(OBJ3)
Way two:
1 ImportSettings2 3 defSingleton (CLS):4_instance =CLS (Settings. IP, settings. PORT)5 6 defWrapper (*args, * *Kwargs):7 ifArgsorKwargs:8obj = CLS (*args, * *Kwargs)9 returnobjTen return_instance One A returnwrapper - - @singleton the classMySQL: - def __init__(self, IP, port): -Self.ip =IP -Self.port =Port + -Obj1 =MySQL () +Obj2 =MySQL () AObj3 =MySQL () at Print(OBJ1) - Print(OBJ2) - Print(OBJ3)
Way three:
1 ImportSettings2 3 classMymeta (type):4 def __init__(self, class_name, class_bases, class_dic):5Self.__instance=Self (settings. IP, settings. PORT)6 7 def __call__(Self, *args, * *Kwargs):8 ifArgsorKwargs:9obj = self.__new__(self)TenSelf.__init__(obj, *args, * *Kwargs) One returnobj A Else: - returnSelf.__instance - the classMySQL (metaclass=Mymeta): - def __init__(self, IP, port): -Self.ip =IP -Self.port =Port + -Obj1 =MySQL () +Obj2 =MySQL () AObj3 =MySQL () at Print(OBJ1) - Print(OBJ2) - Print(OBJ3)
Mode four:
1 defF1 ():2 fromSingletonImportinstance3 Print(instance)4 5 defF2 ():6 fromSingletonImportInstance,mysql7 Print(instance)8obj = MySQL ('1.1.1.1','3389')9 Print(obj)Ten One F1 () A F2 () - - the content in singleton.py file: - ImportSettings - - classMySQL: + Print('Run ...') - + def __init__(self, IP, port): ASelf.ip =IP atSelf.port =Port - -Instance = MySQL (settings. IP, settings. PORT)
Python single-instance mode