python设计模式之享元模式
意图
- 运用共享技术有效地支持大量细粒度的对象
特点
- 享元模式的特点是,复用我们内存中已存在的对象,降低系统创建对象实例的性能消耗
逻辑图如下
不适用享元模式
使用享元模式
使用场景
- 当我们发现某个类型的对象有大量的实例时,我们是否可以对这些实例进行分类,经过分类后,我们发现只有很少的类别的情况下
- 我们发现通过使用享元模式后能够提高系统的性能和不会带来更多的复杂度时
- 一般是给出本地内存资源节省的一个方案
例子
import weakref
class Card(object):
"""The object pool. Has builtin reference counting"""
_CardPool = weakref.WeakValueDictionary()
"""Flyweight implementation. If the object exists in the
pool just return it (instead of creating a new one)"""
def __new__(cls, value, suit):
obj = Card._CardPool.get(value + suit, None)
if not obj:
obj = object.__new__(cls)
Card._CardPool[value + suit] = obj
obj.value, obj.suit = value, suit
return obj
def __repr__(self):
return "<Card: %s%s>" % (self.value, self.suit)
if __name__ == '__main__':
c1 = Card('9', 'h')
c2 = Card('9', 'h')
print(c1, c2)
print(c1 == c2)
print(id(c1), id(c2))