'''
单例模式:存的一样的才用单例模式
1 使用类方法
2 装饰器实现
3 使用元类
'''
# import settings
#使用类方法
# class Mysql:
# __instance=None
# def __init__(self,ip,port):
# self.ip=ip
# self.port=port
#
# @classmethod
# def from_conf(cls):
# if cls.__instance is None:
# cls.__instance=cls(settings.IP,settings.PORT)
# return cls.__instance
#
# obj1=Mysql.from_conf()
# obj2=Mysql.from_conf()
#
# print(obj1)
# print(obj2)
# class Mysql:
# __instance=None
# def __init__(self,ip,port):
# self.ip=ip
# self.port=port
# @classmethod
# def from_conf(cls):
# if cls.__instance is None:
# cls.__instance=cls(settings.IP,settings.PORT)
# return cls.__instance
#装饰器实现
def singleton(cls):
_instance=cls(settings.IP,settings.PORT)
def wrapper(*args,**kwargs):
if len(args)==0 and len(kwargs)==0:
return _instance
return cls(*args,**kwargs)
return wrapper
@singleton
class Mysql:
def __init__(self,ip,port):
self.ip=ip
self.port=port
obj1=Mysql()
print(obj1)
obj2=Mysql()
print(obj1)
print(obj2)
obj3=Mysql('1.1.1.1',3306)
print(obj3)
#使用元类实现
# 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, settings.IP, settings.PORT) #名称空间传默认值
#
# def __call__(self, *args, **kwargs):#如果没传值以默认为准(在类定义阶段就创建好了),如果传值以此为准
# # call则是在对象实例化的时候使用
# if len(args)==0 and len(kwargs)==0:
# return self.__instance
# obj = self.__new__(self) #调用self(mysql类)的__new__方法,创建一个对象的名称空间并将名称空间命名为obj
# self.__init__(obj, *args, **kwargs) #将args,kwargs传给obj空间,是obj独有的属性
# return obj #返回obj对象
#
#
# class Mysql(object,metaclass=Mymeta):
# def __init__(self,ip,port):
# self.ip=ip
# self.port=port
# obj1=Mysql()
# print(obj1)
# obj2=Mysql()
# print(obj1)
# print(obj2)
# obj3=Mysql('1.1.1.1',3306)
# print(obj3)