Singleton Sample:
见http://en.wikipedia.org/wiki/Singleton_pattern
特性:
-
instance全局唯一
-
通过getInstance作为该instantce唯一接口
该模式的不足:
-
内存泄露问题,由于使用静态变量,会和全局变量放在内存的static区域,程序结束之后才释放。
-
多个实例的情况无法支持
-
由于无法被重写,不易于扩展
在python中结合动态语言特性,Borg模式很好的解决了这个问题,做到类的实例共享一组变量(dict), 可以被重载。内存泄露情况依然存在。
Borg:
class Borg:
__shared_state ={}
def __init__(self):
# the different instance's __dict__ point to __shared_state
self.__dict__ =self.__shared_state
Borg模式在大多动态语言中都可以做到很方便的实现。
参考: