Skip to content

Commit 1ad8e44

Browse files
authored
Add flyweight pattern
1 parent 0d3b4b7 commit 1ad8e44

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

structural_patterns/flyweight.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import random
2+
3+
from dataclasses import dataclass
4+
5+
6+
# Flyweight class
7+
@dataclass
8+
class TreeType:
9+
name: str
10+
color: str
11+
texture: str
12+
13+
def draw(self, canvas, x, y):
14+
print(f'Drawing the tree on x: {x} and y: {y} in canvas: {canvas} 🖼️')
15+
16+
17+
# Flyweight factory
18+
class TreeFactory:
19+
20+
def __init__(self, tree_types=[]):
21+
self.tree_types = tree_types
22+
23+
def get_tree_type(self, name, color, texture):
24+
tree_type = self._find_existing_free_type(name, color, texture)
25+
26+
if tree_type == None:
27+
tree_type = TreeType(name, color, texture)
28+
self.tree_types.append(tree_type)
29+
30+
return tree_type
31+
32+
def _find_existing_free_type(self, name, color, texture):
33+
for tree_type in self.tree_types:
34+
if (tree_type.name, tree_type.color, tree_type.texture) == (name, color, texture):
35+
print(f'-> Existing tree type founded {name}-{color}-{texture} 😲')
36+
return tree_type
37+
38+
return None
39+
40+
41+
@dataclass
42+
class Tree:
43+
x: int
44+
y: int
45+
tree_type: TreeType
46+
47+
def draw(self, canvas):
48+
self.tree_type.draw(canvas, self.x, self.y)
49+
50+
51+
class Forest:
52+
def __init__(self, trees=[]):
53+
self.trees = trees
54+
55+
def plant_tree(self, x, y, name, color, texture):
56+
tree_type = TreeFactory().get_tree_type(name, color, texture)
57+
tree = Tree(x, y, tree_type)
58+
59+
print('Planting a tree 🌴')
60+
61+
self.trees.append(tree)
62+
63+
def draw(self, canvas):
64+
for tree in self.trees:
65+
tree.draw(canvas)
66+
67+
68+
if __name__ == '__main__':
69+
forest = Forest()
70+
71+
forest.plant_tree(3, 4, 'Palm', 'Green', 'palm.png')
72+
forest.plant_tree(10, 41, 'Palm', 'Green', 'palm.png')
73+
forest.plant_tree(2, 40, 'Passion fruit', 'Yellow', 'passion_fruit.png')
74+
75+
forest.draw('Empty_canvas')

0 commit comments

Comments
 (0)