The before code creates a new Tree object with full data for each instance, wasting memory. The after code separates shared data (TreeType) and unique data (coordinates), reusing TreeType objects to save memory.
### Before Flyweight (naive, no sharing)
class Tree:
def __init__(self, x, y, type_):
self.x = x
self.y = y
self.type = type_ # large data like tree type info
# Creating many trees with repeated type data
forest = [Tree(i, j, 'Oak') for i in range(1000) for j in range(1000)]
### After Flyweight (shared intrinsic state)
class TreeType:
def __init__(self, name, color, texture):
self.name = name
self.color = color
self.texture = texture
class TreeFactory:
_tree_types = {}
@classmethod
def get_tree_type(cls, name, color, texture):
key = (name, color, texture)
if key not in cls._tree_types:
cls._tree_types[key] = TreeType(name, color, texture)
return cls._tree_types[key]
class Tree:
def __init__(self, x, y, tree_type):
self.x = x
self.y = y
self.tree_type = tree_type # shared intrinsic state
# Creating many trees sharing TreeType objects
forest = []
for i in range(1000):
for j in range(1000):
tree_type = TreeFactory.get_tree_type('Oak', 'Green', 'Rough')
forest.append(Tree(i, j, tree_type))