享元設計模式


享元(flyweight)設計模式屬於結構設計模式類別。 它提供了一種減少物件數的方法。 它包含各種有助於改進應用程式結構的功能。享元物件最重要的特性是不可變的。 這意味著一旦構建就不能修改它們。 該模式使用HashMap來儲存參照物件。

如何實現享元(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()

執行上述程式生成以下輸出 -