Python 享元模式

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

 

如何实现享元模式模式?

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

# Filename : example.py
# Date : 2020-08-22
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()

 

输出

上面的程序生成以下输出:

id = 4368211632
ComplexPatter[ATAG]TooHugeinSize
id = 4363253168
ComplexPatter[AAGT]TooHugeinSize
id = 4368211632
ComplexPatter[ATAG]TooHugeinSize
similar id's says that they are same objects

抽象工厂模式也称为工厂工厂。该设计模式属于创新设计模式类别。它提供了创建对象的最佳方法之一。它包含一个接口,负责创建与Factory相关的对象。 如何实现抽象工厂模式?以下程序有助于实现抽象工厂模式。# ...