design-patterns/structural/flyweight/flyweight_factory.py
Ruidy 664b39c32e
Flyweight Pattern (#12)
* edit documentation

* add code example

Co-authored-by: Ruidy <r.nemausat@empfohlen.de>
2020-09-27 21:25:55 +02:00

44 lines
1.5 KiB
Python

from typing import Dict, List
from structural.flyweight.flyweight import Flyweight
class FlyweightFactory:
"""
The Flyweight Factory creates and manages the Flyweight objects. It ensures
that flyweights are shared correctly. When the client requests a flyweight,
the factory either returns an existing instance or creates a new one, if it
doesn't exist yet.
"""
_flyweights: Dict[str, Flyweight] = {}
def __init__(self, initial_flyweights: List) -> None:
for state in initial_flyweights:
self._flyweights[self.get_key(state)] = Flyweight(state)
def get_key(self, state: List) -> str:
"""
Returns a Flyweight's string hash for a given state.
"""
return "_".join(sorted(state))
def get_flyweight(self, shared_state: List) -> Flyweight:
"""
Returns an existing Flyweight with a given state or creates a new one.
"""
key = self.get_key(shared_state)
if not self._flyweights.get(key):
print("FlyweightFactory: Can't find a flyweight, creating new one.")
self._flyweights[key] = Flyweight(shared_state)
else:
print("FlyweightFactory: Reusing existing flyweight.")
return self._flyweights[key]
def list_flyweights(self) -> None:
count = len(self._flyweights)
print(f"FlyweightFactory: I have {count} flyweights:")
print("\n".join(map(str, self._flyweights.keys())), end="")