1. 程式人生 > >單例的三種實現方式

單例的三種實現方式

In imp SQ span wrap 定制 bsp () import

一:類方法實現單例

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)#初始化一個類(mysql)
        self.__instance = object.__new__(self)#利用mysql類的基類__new__方法造出一個mysql類的對象
self.__init__(self.__instance,setting.host,setting.port)#調用類的__init__方法實例化出這個對象 def __call__(self, *args, **kwargs): #如果對元類的實例化對象mysql類加括號調用則自動觸發,元類的對象類mysql會作為第一個參數自動傳入 #相當於mysql.__call__() if args or kwargs: obj = object.__new__(self) self.
__init__(obj,*args,**kwargs) return obj return self.__instance class Mysql(metaclass=Mymeta):#定義類mysql(實際就是(調用元類的_init__方法)) def __init__(self,host,port): self.host = host self.port = port obj1 = Mysql()#加括號調用,實例化生成對象(調用類的__init__方法) 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 = cls(*args, **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

附:setting.py

port = 8888
host = "127.0.0.1"

單例的三種實現方式