大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。
实现单例模式的三种方法:类实现、装饰器实现和元类实现
#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))
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/120211.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...