实现单例模式的三种方法:类实现、装饰器实现和元类实现
#coding-utf-8 #单例模式 #类的方式实现单例模式 '''class Singleton(object): _instance = None def __init__(self): print ("__init__") pass @staticmethod def __new__(cls, *argv, **kwargv): print ("__new__") if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls,*argv, **kwargv) return cls._instance class A(Singleton):pass''' #使用装饰器的方式实现单例模式 '''def Singleton(cls): instances = {} def getinstance(*argv, **kwargv): if cls not in instances: instances[cls] = cls(*argv, **kwargv) return instances[cls] return getinstance @Singleton class A(object): def __init__(self, parm): print ("class A __init__:%s" %(parm))''' #使用元类的方法实现单例模式 class Singleton(type): instances = {} def __call__(self, *argv, **kwargv): if self not in self.instances: print ("!!!not have instances") self.instances[self] = super(Singleton, self).__call__(*argv, **kwargv) return super(Singleton, self).__call__(*argv, **kwargv) def __new__(mcs, name, bases, namespace, **kwargs): print ("Singleton new") return super(Singleton, mcs).__new__(mcs,name, bases, namespace, **kwargs) class A(metaclass = Singleton): def __init__(self): self.aa = 1 if __name__ == "__main__": a = A() b = A() print (id(a)) print (id(b))