python singleton

时间:2024-09-17 14:05:20

方法一:用元类的方式实现一个singleton。

liuxiaoyan@development:~/mysite$ cat Singleton.py
class Singleton(type):
"""Singleton Metaclass"""
def __init__(cls, name, bases, dic):
super(Singleton, cls).__init__(name, bases, dic)
cls.instance = None def __call__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls.instance class MyClass(object):
__metaclass__ = Singleton def __init__(self,arg):
self.arg = arg myClass1=MyClass("myClass1")
myClass2=MyClass("myClass2") print myClass1 is myClass2
liuxiaoyan@development:~/mysite$ python Singleton.py
True

方法二:用修饰类的方式实现一个Singleton。

liuxiaoyan@development:~/mysite$ cat Singleton.py
class Singleton:
def __init__( self, decorated ):
self._decorated = decorated
def Instance( self ):
try:
return self._instance
except AttributeError:
self._instance = self._decorated
return self._instance def __call__( self ):
raise TypeError( 'single instance allowed' ) @Singleton
class MyClass:
def __init__( self ):
print( 'created' )
#myClass=MyClass() #不能再用这种方式创建MyClass实例,会产生异常 #用以下方法创建实例
myClass1=MyClass.Instance()
myClass2=MyClass.Instance() print myClass1 is myClass2
print id(myClass1)
print id(myClass2) liuxiaoyan@development:~/mysite$ python Singleton.py
True
140716352778528
140716352778528