## page was renamed from zhArticleTemplate ##language:zh #pragma section-numbers on -- flyaflya [<>] <> == 模式名称 == === FlyweightPattern === 运用共享技术有效地支持大量细粒度的对象。 === 代码 === {{{ #!python #实现过程类似于singleton模式 import weakref #weekref产生的value不能保持对象存在。当对象不包括weakref在内的引用计数达到0时,对象将被删除。 class Instrument(object): _InstrumentPool = weakref.WeakValueDictionary() def __new__(cls, name): '''Instrument(name) Create a new instrument object, or return an existing one''' obj = Instrument._InstrumentPool.get(name, None) if not obj: print "new",name obj = object.__new__(cls) Instrument._InstrumentPool[name] = obj return obj def __init__(self, name): '''Complete object construction''' self.name = name print "New instrument @%04x, %s" % (id(self), name) # ... connect instrument to datasource ... }}} ===  测试例子  === {{{ #!python import unittest class InstrumentTests(unittest.TestCase): def testInstrument(self): ibm1 = Instrument("IBM") ms = Instrument("MS") ibm2 = Instrument("IBM") self.assertEquals(id(ibm1), id(ibm2)) self.assertNotEquals(id(ibm1), id(ms)) self.assertEquals(2, len(Instrument._InstrumentPool), "Total instruments allocated") # This bit assumes CPython memory allocation: del(ibm1) del(ibm2) # 每一次调用Instrument,因其函数__new__中的Instrument._InstrumentPool[name]是weakref,只有obj = object.__new__(cls)引用一次。所以del(ibm1)和del(imb2)后引用计数达到0,对象被清理。 self.assertEquals(1, len(Instrument._InstrumentPool), "Total instruments allocated") if __name__=='__main__': unittest.main() }}} === 特殊说明 ===