1. 程式人生 > >飄逸的python - 單例模式亂彈

飄逸的python - 單例模式亂彈

trac obj single not def pop nbsp asa sel

方法一:裝飾器

利用“裝飾器只會執行一次”這個特點

 1 def singleton(cls):
 2     instances = []# 為什麽這裏不直接為None,因為內部函數沒法訪問外部函數的非容器變量
 3     def getinstance(*args, **kwargs):
 4         if not instances:
 5             instances.append(cls(*args, **kwargs))
 6         return instances[0]
 7     return getinstance
 8 
 9 @singleton
10 class Foo: 11 a = 1 12 13 f1 = Foo() 14 f2 = Foo() 15 print id(f1), id(f2)

方法二:基類

利用“類變量對所有對象唯一”,即cls._instance

1 class Singleton(object):
2     def __new__(cls, *args, **kwargs):
3         if not hasattr(cls, _instance):
4             cls._instance = object.__new__(cls, *args, **kwargs)
5 return cls._instance 6 7 class Foo(Singleton): 8 a = 1

方法三:metaclass

利用“類變量對所有對象唯一”,即cls._instance

1 class Singleton(type):
2     def __call__(cls, *args, **kwargs):
3         if not hasattr(cls, _instance):
4             cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
5 return cls._instance 6 7 class Foo(): 8 __metaclass__ = Singleton

方法四:Borg模式

利用“類變量對所有對象唯一”,即__share_state

1 class Foo:
2    __share_state = {}
3    def __init__(self):
4        self.__dict__ = self.__share_state

方法五:利用import

利用“模塊只會被import一次”

1 #在文件mysingleton中
2 class Foo(object):
3      pass
4 
5 f = Foo()

然後在其它模塊,from mysingleton import f
直接拿f當作單例的對象來用

轉自:http://blog.csdn.net/handsomekang/article/details/46672047

飄逸的python - 單例模式亂彈