本文主要是介绍python 设计模式-享元模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
享元模式是一种比较简单的设计模式,用的也比较多,他可以有效复用对象,在一定程度上提高程序的性能。我们常见的池化技术其实就是享元模式的一类实现。代码示例:
from abc import ABCMeta, abstractmethodclass FlyWeight(metaclass=ABCMeta):def __init__(self, extrinsic):self._extrinsic = extrinsic@propertydef extrinsic(self):return self._extrinsic@propertydef intrinsic(self):return self._intrinsic@intrinsic.setterdef intrinsic(self, value):self._intrinsic = value@abstractmethoddef oper(self):passclass ConcreteFlyWeight(FlyWeight):def oper(self):self.intrinsic = 'intrinsic attr'print('oper in concrete flyweight, intrinsic: {}, extrinsic: {}'.format(self.intrinsic, self.extrinsic))class FlyWeightFactory:_flyweights = {}def get_flyweight(self, extrinsic):return self._flyweights.setdefault(extrinsic, ConcreteFlyWeight(extrinsic))if __name__ == '__main__':fac = FlyWeightFactory()a = fac.get_flyweight('a')a.oper()
输出:
oper in concrete flyweight, intrinsic: intrinsic attr, extrinsic: a
这篇关于python 设计模式-享元模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!