享元模式
模式说明
所谓享元模式就是运行共享技术有效地支持大量细粒度对象的复用。系统使用少量对象,而且这些都比较相似,状态变化小,可以实现对象的多次复用。
FlyweightFactory内定义的实体是不变的(共享的),传入参数是状态变化。
缓存形式,传入参数已经被缓存则直接返回,否则创建参数对应实体,放入缓存并返回该新实体
模式结构图

程序示例
说明:一个图形类,原型派生类;颜色状态变化;享元工厂;
代码:
class Shape(object):
def __init__(self,color):
self._color = color
def draw(self):
print 'color:%s shape:%s'%(self._color,self.__class__.__name__)
class Circle(Shape):
pass
class FlyweightFactory(object):
def __init__(self):
self._shapes = {}
def getshape(self,color):
if color in self._shapes.keys():
return self._shapes[color]
else:
temp = Circle(color)
self._shapes[color]=temp
return temp
def getcount(self):
print len(self._shapes.keys())
if __name__=='__main__':
factory = FlyweightFactory()
shape = factory.getshape('red')
shape.draw()
shape = factory.getshape('black')
shape.draw()
shape = factory.getshape('red')
shape.draw()
factory.getcount()
运行结果:

参考来源:
http://www.cnblogs.com/chenssy/p/3679190.html
http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html
http://www.cnblogs.com/Terrylee/archive/2006/07/17/334911.html
