- Python 設計模式教程
- Python 設計模式 - 主頁
- 引言
- Python 設計模式 - 要點
- MVC 模式 (Model View Controller)
- Python 設計模式 - 單例
- Python 設計模式 - 工廠
- Python 設計模式 - 建造者
- Python 設計模式 - 原型
- Python 設計模式 - 外觀
- Python 設計模式 - 命令
- Python 設計模式 - 介面卡
- Python 設計模式 - 裝飾器
- Python 設計模式 - 代理
- 職責鏈模式
- Python 設計模式 - 觀察者
- Python 設計模式 - 狀態
- Python 設計模式 - 策略
- Python 設計模式 - 模板方法
- Python 設計模式 - 輕量級 (Flyweight)
- 抽象工廠
- 面向物件
- 面向物件概念實現
- Python 設計模式 - 迭代器
- 字典
- 連結串列資料結構
- Python 設計模式 - 集合
- Python 設計模式 - 佇列
- 字串和序列化
- Python 併發
- Python 設計模式 - 反
- 異常處理
- Python 設計模式資源
- 快速指南
- Python 設計模式 - 資源
- 討論
Python 設計模式 - 輕量級 (Flyweight)
輕量級模式屬於結構設計模式類別。此種模式提供減少物件數量的方法。它包含各種有助於改進應用程式結構的特性。輕量級物件最重要的特性是不變性。這意味著它們在構建後不能修改。這種模式使用 HashMap 儲存引用物件。
如何實現輕量級模式?
以下程式有助於實現輕量級模式 −
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()
輸出
以上程式生成以下輸出 −
廣告