第一种:类方法实现单例
方式一:类方法实现单例模式
class Mysql:
__instance = None
def __init__(self,host,port):
self.host = host
self.port = port q
@classmethod
def singleton(cls):
if not cls.__instance:
cls.__instance = cls(setting.host,setting.port)
return cls.__instance
obj1 = Mysql.singleton()
obj2 = Mysql.singleton()
print(obj1)
print(obj2)
第二种:自定制元类方法实现单例
import setting
class Mymeta(type):
def __init__(self,class_name,base,dic):
super().__init__(class_name, base, dic)
self.__instance = object.__new__(self)
self.__init__(self.__instance,setting.host,setting.port)
def __call__(self, *args, **kwargs):
if args or kwargs:
obj = object.__new__(self)
self.__init__(obj,*args,**kwargs)
return obj
return self.__instance
class Mysql(metaclass=Mymeta):
def __init__(self,host,port):
self.host = host
self.port = port
obj1 = Mysql()
obj2 = Mysql()
print(obj1)
print(obj2)
obj3 = Mysql("129.0.0.1",8080)
obj4 = Mysql("129.0.0.1",8080)
print(obj3)
print(obj4)
第三种:自定制元类方法实现单例
def sigleton(cls):
__instance = cls(setting.host,setting.port)
def wrapper(*args,**kwargs):
if args or kwargs:
obj = object.__new__(cls)
cls.__init__(obj,*args, **kwargs)
return obj
return __instance
return wrapper
@sigleton
class Mysql:
def __init__(self,host,port):
self.host = host
self.port = port
port = 8888
host = "127.0.0.1"