Skip to content

Commit 6b5512c

Browse files
committed
🔧 Adding
Flyweight Pattern
1 parent aa66345 commit 6b5512c

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Flyweight
2+
3+
from typing import List, Dict, Tuple
4+
5+
6+
class TreeType:
7+
def __init__(self, name, color, texture):
8+
self.name = name
9+
self.color = color
10+
self.texture = texture
11+
12+
def draw(self, canvas, x, y):
13+
print(f"[Drawing] {self.name} tree at ({x}, {y})"
14+
f"with color {self.color} and texture {self.texture} on {canvas}")
15+
16+
17+
# Flyweight Factory
18+
19+
class TreeFactory:
20+
_tree_types: Dict[Tuple[str, str, str], TreeType] = {}
21+
22+
@classmethod
23+
def get_tree_type(cls, name, color, texture):
24+
key = (name, color, texture)
25+
26+
if key not in cls._tree_types:
27+
print(f"[Factory] Creating a new treeType: {key}")
28+
cls._tree_types[key] = TreeType(name, color, texture)
29+
else:
30+
print(f"[factory] Reusing existing TreeType: {key}")
31+
return cls._tree_types[key]
32+
33+
34+
# Context
35+
36+
class Tree:
37+
def __init__(self, x, y, tree_type: TreeType):
38+
self.x = x
39+
self.y = y
40+
self.tree_type = tree_type
41+
42+
def draw(self, canvas):
43+
self.tree_type.draw(canvas, self.x, self.y)
44+
45+
46+
# Client
47+
48+
class Forest:
49+
def __init__(self):
50+
self.trees: List[Tree] = []
51+
52+
def plant_tree(self, x, y, name, color, texture):
53+
tree_type = TreeFactory.get_tree_type(name, color, texture)
54+
tree = Tree(x, y, tree_type)
55+
self.trees.append(tree)
56+
57+
def draw(self, canvas):
58+
for tree in self.trees:
59+
tree.draw(canvas)
60+
61+
62+
# Demo
63+
64+
if __name__ == "__main__":
65+
forest = Forest()
66+
67+
# Plant many trees but with only 2 types
68+
for i in range(0, 10, 2):
69+
forest.plant_tree(i, i + 1, "Oak", "Green", "Rough")
70+
forest.plant_tree(i + 1, i + 2, "Pine", "Dark green", "Smooth")
71+
72+
print("\n=========Drawing Forest========")
73+
forest.draw("Canvas1")

0 commit comments

Comments
 (0)