单例模式

四种方式实现单例模式

一、类内部定义静态方法

IP = '127.0.0.1'
PORT = 3306

class MySQL:
    _instance = None
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
    
    @classmethod
    def from_conf(cls):
        if not _instance:
            cls._instance = cls(IP, PORT)
        return cls._instance

二、装饰器实现单例模式

def singleton(cls):
    cls.__instance = cls(IP, PORT)
    
    def wrapper(*args, **kwargs):
        if len(args) == 0 and kwargs == 0:
            return cls.__instance
    	
        return cls(*args, **kwargs)
   
@singleton
class MySQL:
    def __init__(self, ip, port):
        self.ip = ip
        self.prot = port

三、通过元类实现单例模式

class Mymate(type):
    def __init__(self, name, bases, dic):
        self.__instance = self(IP, PORT)
    def __call__(self, *args, **kwargs):
        if len(args) == 0 and len(kwargs) == 0:
            return self.__instance
       	obj = object.__new__(cls)
        obj.__init__(self, *args, **kwargs)
        return obj

四、通过模块导入的方式实现单例

请自行脑补实现过程

原文地址:https://www.cnblogs.com/17vv/p/11459663.html