单例模式
多次实例化的结果指向同一个实例
单例模式实现方式
1 import settings 2 3 #方式一: 4 class MySQL: 5 __instance=None 6 def __init__(self,ip,port): 7 self.ip =ip 8 self.port=port 9 @classmethod 10 def from_conf(cls): 11 if cls.__instance is None: 12 cls.__instance=cls(settings.IP,settings.PORT) 13 return cls.__instance 14 obj1=MySQL.from_conf() 15 obj2=MySQL.from_conf() 16 obj3=MySQL.from_conf() 17 obj4=MySQL('1.1.1.3',3309) 18 print(obj1) 19 print(obj2) 20 print(obj3)
1 import settings 2 3 #方式二: 4 def singleton(cls): 5 __instance=cls(settings.IP,settings.PORT) 6 def wrapper(*args,**kwargs): 7 if len(args) !=0 or len(kwargs) !=0: 8 obj=cls(*args,**kwagrs) 9 return obj 10 return __instance 11 return wrappers 12 13 @singleton 14 class MySQL: 15 def __init__(self,ip,port) 16 self.ip=ip 17 self.port=port 18 19 obj1=MySQL.from_conf() 20 obj2=MySQL.from_conf() 21 obj3=MySQL.from_conf() 22 obj4=MySQL('1.1.1.3',3309) 23 print(obj1) 24 print(obj2) 25 print(obj3) 26 print(obj4)
1 import settings 2 3 #实例三 4 5 class Mymeta(type): 6 def __init__(self,class_name,class_bases,class_dic): 7 #self=MySQL这个类 8 self.__instance=self(settings.IP,settings.OPRT) 9 10 def __call__(self,*args,**kwargs): 11 #self=MySQL这个类 12 if len(args) !=0 or len(kwargs) !=0: 13 obj=self.__new__(self) 14 self.__init__(obj,*args,**kwargs) 15 return obj 16 else: 17 return self.__instance 18 19 class MySQL(metaclass=Mymeta):#Mymeta(...) 20 def __init__(self,ip,port): 21 self.ip=ip 22 self.port=port 23 24 obj1=MySQL() 25 obj2=MySQL() 26 obj3=MySQL() 27 obj4=MySQL('1.1.1.3',3302) 28 print(obj1) 29 print(obj2) 30 print(obj3) 31 print(obj4)
1 #实例四 2 3 def f1(): 4 from singleton import intance 5 print(instance) 6 7 def f2(): 8 from singleton import instance,MySQL 9 print(instance) 10 obj=MySQL('1.1.1.3',3302) 11 print(obj) 12 13 f1() 14 f2() 15 16 #该方法还需创建一个 singleton.py 的文件,内容如下: 17 18 import settings 19 20 class MySQL: 21 print('run...') 22 def __init__(self,ip,port): 23 self.ip=ip 24 self.port=port 25 26 instance=MySQL(settings.IP,settings.PORT)