单实例模式一直是常用的设计模式,对于python的单实例模式,其实其本身就有实现
里面说到module,module只会初始化一次,天然的singleton。这是最为python的解决方案。将你所需要的属性和方法,直接暴露在模块中变成模块的全局变量和方法即可。
另外,如果真的要使用代码进行singleton,下面给出几个代码
# Singleton/ClassVariableSingleton.py class SingleTone(object): __instance = None def __new__(cls, val): if SingleTone.__instance is None: SingleTone.__instance = object.__new__(cls) SingleTone.__instance.val = val return SingleTone.__instance
# Singleton/SingletonDecorator.py class SingletonDecorator: def __init__(self,klass): self.klass = klass self.instance = None def __call__(self,*args,**kwds): if self.instance == None: self.instance = self.klass(*args,**kwds) return self.instance class foo: pass foo = SingletonDecorator(foo) x=foo() y=foo() z=foo() x.val = ‘sausage‘ y.val = ‘eggs‘ z.val = ‘spam‘ print(x.val) print(y.val) print(z.val) print(x is y is z)
# Singleton/SingletonMetaClass.py class SingletonMetaClass(type): def __init__(cls,name,bases,dict): super(SingletonMetaClass,cls) .__init__(name,bases,dict) original_new = cls.__new__ def my_new(cls,*args,**kwds): if cls.instance == None: cls.instance = original_new(cls,*args,**kwds) return cls.instance cls.instance = None cls.__new__ = staticmethod(my_new) class bar(object): __metaclass__ = SingletonMetaClass def __init__(self,val): self.val = val def __str__(self): return `self` + self.val x=bar(‘sausage‘) y=bar(‘eggs‘) z=bar(‘spam‘) print(x) print(y) print(z) print(x is y is z)
时间: 2024-12-16 23:48:55