0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[FlyweightPatter]wikiのサンプルをpython3で実装

Posted at
flyweight_pattern_wiki.py
"""Flyweight Pattern
https://ja.wikipedia.org/wiki/Flyweight_%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3

Desc:
等価なインスタンスを[別々の箇所]で使用する際に、
一つのインスタンスを再利用することによって、
プログラムを省リソース化することを目的とする。

(UML
FlyweightFactory  <>-------------- Flyweight
- pool:Flyweight[]
+ getFlyweight()

(Ex
StampFactory      <>-------------- Stamp
- pool: Stamp[]
+ get()
"""

# Flyweight
class Stamp:

    def __init__(self, type: str):
        self.__type = type

    def print(self):
        print(self.__type)

# FlyweightFactory
class StampFactory:

    def __init__(self):
        self.__pool = {}

    # FlyweightFactory.getFlyweight()
    def get(self, type: str) -> Stamp:
        if type not in self.__pool:
            self.__pool[type] = Stamp(type)
        return self.__pool[type]

    @property
    def pool_size(self) -> int:
        return len(self.__pool)


if __name__ == '__main__':
    factory = StampFactory()
    stamps = []

    for c in 'たかいたけたてかけた':
        stamps.append(factory.get(c))

    for stamp in stamps:
        stamp.print()

    print('StampFactory pool size=', factory.pool_size)


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?