MCPcopy Create free account
hub / github.com/RefactoringGuru/design-patterns-python / FlyweightFactory

Class FlyweightFactory

src/Flyweight/Conceptual/main.py:42–92  ·  view source on GitHub ↗

EN: 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. RU: Фабрика Легковесов созд

Source from the content-addressed store, hash-verified

40
41
42class FlyweightFactory():
43 """
44 EN: The Flyweight Factory creates and manages the Flyweight objects. It
45 ensures that flyweights are shared correctly. When the client requests a
46 flyweight, the factory either returns an existing instance or creates a new
47 one, if it doesn't exist yet.
48
49 RU: Фабрика Легковесов создает объекты-Легковесы и управляет ими. Она
50 обеспечивает правильное разделение легковесов. Когда клиент запрашивает
51 легковес, фабрика либо возвращает существующий экземпляр, либо создает
52 новый, если он ещё не существует.
53 """
54
55 _flyweights: Dict[str, Flyweight] = {}
56
57 def __init__(self, initial_flyweights: Dict) -> None:
58 for state in initial_flyweights:
59 self._flyweights[self.get_key(state)] = Flyweight(state)
60
61 def get_key(self, state: Dict) -> str:
62 """
63 EN: Returns a Flyweight's string hash for a given state.
64
65 RU: Возвращает хеш строки Легковеса для данного состояния.
66 """
67
68 return "_".join(sorted(state))
69
70 def get_flyweight(self, shared_state: Dict) -> Flyweight:
71 """
72 EN: Returns an existing Flyweight with a given state or creates a new
73 one.
74
75 RU: Возвращает существующий Легковес с заданным состоянием или создает
76 новый.
77 """
78
79 key = self.get_key(shared_state)
80
81 if not self._flyweights.get(key):
82 print("FlyweightFactory: Can't find a flyweight, creating new one.")
83 self._flyweights[key] = Flyweight(shared_state)
84 else:
85 print("FlyweightFactory: Reusing existing flyweight.")
86
87 return self._flyweights[key]
88
89 def list_flyweights(self) -> None:
90 count = len(self._flyweights)
91 print(f"FlyweightFactory: I have {count} flyweights:")
92 print("\n".join(map(str, self._flyweights.keys())), end="")
93
94
95def add_car_to_police_database(

Callers 1

main.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected