This repository has been archived by the owner on Dec 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 366
/
flywight_pattern.py
73 lines (50 loc) · 2.08 KB
/
flywight_pattern.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import json
from typing import Dict
class Flyweight():
def __init__(self, shared_state: str) -> None:
self._shared_state = shared_state
def operation(self, unique_state: str) -> None:
s = json.dumps(self._shared_state)
u = json.dumps(unique_state)
print(f"Flyweight: Displaying shared ({s}) and unique ({u}) state.", end="")
class FlyweightFactory():
_flyweights: Dict[str, Flyweight] = {}
def __init__(self, initial_flyweights: Dict) -> None:
for state in initial_flyweights:
self._flyweights[self.get_key(state)] = Flyweight(state)
def get_key(self, state: Dict) -> str:
return "_".join(sorted(state))
def get_flyweight(self, shared_state: Dict) -> Flyweight:
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="")
def add_car_to_police_database(
factory: FlyweightFactory, plates: str, owner: str,
brand: str, model: str, color: str
) -> None:
print("\n\nClient: Adding a car to database.")
flyweight = factory.get_flyweight([brand, model, color])
flyweight.operation([plates, owner])
if __name__ == "__main__":
factory = FlyweightFactory([
["Chevrolet", "Camaro2018", "pink"],
["Mercedes Benz", "C300", "black"],
["Mercedes Benz", "C500", "red"],
["BMW", "M5", "red"],
["BMW", "X6", "white"],
])
factory.list_flyweights()
add_car_to_police_database(
factory, "CL234IR", "James Doe", "BMW", "M5", "red")
add_car_to_police_database(
factory, "CL234IR", "James Doe", "BMW", "X1", "red")
print("\n")
factory.list_flyweights()