Flyweightパターン
from 20241118
Flyweight パターン
同一の内容を持つオブジェクトを複数回作成する場合、1つのインスタンスだけを保持することでメモリ使用量やパフォーマンスの向上を目的とするOOPのデザインパターン。
シングルトンパターンともちょっと似ているがこちらはキャッシュが主な目的。
当然ながら、キャッシュヒット率が高ければ高いほど、一回の操作が高価なほど効果が上がる
Pythonで__new__ メソッドを用いて、タプルをキャッシュする実装
Flyweightパターンと呼ばれるやつ
関数の引数をキャッシュしたいときはfunctools.lru_cacheも利用できる
code:py
class CachedTuple(tuple):
_cache = {}
def __new__(cls, value):
if not isinstance(value, tuple):
raise TypeError("CachedTuple にはタプルのみ渡してください")
try:
h = hash(value)
except TypeError:
raise TypeError("キャッシュするにはハッシュ可能なオブジェクトが必要です")
if h in cls._cache:
return cls._cacheh
instance = super().__new__(cls, value)
cls._cacheh = instance
return instance
# 使用例
a = CachedTuple(("Taro", 22))
b = CachedTuple(("Taro", 22))
c = CachedTuple(("Hanako", 20))
print(a is b) # 出力: True
print(a is c) # 出力: False
# エラーチェック
try:
d = CachedTuple("Taro", 22) # リストはハッシュ不可能
except TypeError as e:
print(e) # 出力: キャッシュするにはハッシュ可能なオブジェクトが必要です