pythonでFlyweightパターン

コード


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

class Stamp:
type = ""
def __init__(self, type):
self.type = type
def execute(self):
if self.type is not "":
print(self.type)

class StampFactory:
pool = ""
def __init__(self):
self.pool = {None:Stamp}
def get(self, type):
self.pool[type] = Stamp(type)
stamp = self.pool[type]
if stamp is None:
stamp = {type:Stamp(type)}
return stamp

class FlyweightTest:
def main(*args):
sf = StampFactory()
stamps = []
stamps.append(sf.get(u"て"))
stamps.append(sf.get(u"す"))
stamps.append(sf.get(u"と"))
stamps.append(sf.get(u"し"))
stamps.append(sf.get(u"て"))
stamps.append(sf.get(u"み"))
stamps.append(sf.get(u"た"))
stamps.append(sf.get(u"て"))
stamps.append(sf.get(u"す"))
stamps.append(sf.get(u"と"))

print("POOL DATA-------------------------------")
for i in sf.pool:
if i is not None:
print i

print("OUTPUT DATA-----------------------------")
for v in stamps: v.execute()

if __name__ == "__main__":
try:
FlyweightTest().main(sys.argv)
except Exception,e:
print(e)

実行結果


mochi@mochi-server:~/src/GoF/python$ ./Flyweight.py
POOL DATA-------------------------------






OUTPUT DATA-----------------------------









こんな感じかな?

参照サイト
http://ja.wikipedia.org/wiki/Flyweight_%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3