单例模式:
什么是单例模式?
基于某种方法实例化多次得到实例是同一个
实现方法:
ip = '1.1.1.1' port = 3306 # 假装来自配置文件 #方法一:定义类方法进行判断 class Mysql: __instance = None def __init__(self, ip, port): self.ip = ip self.port = port @classmethod def from_settings(cls): if not cls.__instance: cls.__instance = cls(ip, port) return cls.__instance p1 = Mysql.from_settings() p2 = Mysql.from_settings() p3 = Mysql.from_settings() p4 = Mysql('1.1.3.2',2203) print(p1 is p2 is p3) # Ture print(p1) print(p4)
#方法二:使用装饰器
def single(cls):
_instance = cls(ip, port)
def inner(*args, **kwargs):
if len(args) + len(kwargs) == 0:
return _instance
return cls(*args, **kwargs)
return inner
@single
class Mysql:
__instance = None
def __init__(self, ip, port):
self.ip = ip
self.port = port
p1 = Mysql()
p2 = Mysql()
p3 = Mysql()
p4 = Mysql('1.1.3.2',2203)
print(p1 is p2 is p3) # True
print(p1)
print(p4)
方法三:使用元类控制
class Mymeta(type):
def __init__(self,class_name,class_bases,class_dic):
super().__init__(class_name,class_bases,class_dic)
self.__instance = self.__new__(self)
self.__init__(self.__instance,ip,port)
def __call__(self, *args, **kwargs):
if len(args) + len(kwargs) == 0:
return self.__instance
obj = self.__new__(self)
self.__init__(obj,*args,**kwargs)
return obj
class Mysql(object,metaclass=Mymeta):
__instance = None
def __init__(self, ip, port):
self.ip = ip
self.port = port
p1 = Mysql()
p2 = Mysql()
p3 = Mysql()
p4 = Mysql('1.1.3.2',2203)
print(p1 is p2 is p3) # True
print(p1)
print(p4)