开发手册 欢迎您!
软件开发者资料库

Python设计模式 - Flyweight

Python设计模式Flyweight - 从简单和简单的步骤学习Python设计模式从基本到高级概念,包括简介,Python的Gist,模型视图控制器,单例,工厂,构建器,原型,外观,命令,适配器,装饰器,代理,责任链,观察员,状态,战略,模板,飞重,抽象工厂,面向对象的模式,面向对象的概念实施,迭代器模式,词典,列表数据结构,集,队列,字符串和序列化,Python中的并发,反模式, 异常处理。

flyweight patterb属于结构设计模式类别.它提供了一种减少对象数量的方法.它包括各种有助于改进应用程序结构的功能. flyweight对象最重要的特性是不可变的.这意味着一旦构造它们就不能被修改.该模式使用HashMap存储引用对象.

如何实现flyweight模式?

以下程序有助于实现flyweight模式 :

class ComplexGenetics(object):   def __init__(self):      pass      def genes(self, gene_code):      return "ComplexPatter[%s]TooHugeinSize" % (gene_code)class Families(object):   family = {}      def __new__(cls, name, family_id):      try:         id = cls.family[family_id]      except KeyError:         id = object.__new__(cls)         cls.family[family_id] = id      return id      def set_genetic_info(self, genetic_info):      cg = ComplexGenetics()      self.genetic_info = cg.genes(genetic_info)      def get_genetic_info(self):      return (self.genetic_info)def test():   data = (('a', 1, 'ATAG'), ('a', 2, 'AAGT'), ('b', 1, 'ATAG'))   family_objects = []   for i in data:      obj = Families(i[0], i[1])      obj.set_genetic_info(i[2])      family_objects.append(obj)      for i in family_objects:      print "id = " + str(id(i))      print i.get_genetic_info()   print "similar id's says that they are same objects "if __name__ == '__main__':   test()

输出

上述程序生成以下输出 :

Flyweight Pattern