Flyweight
medium 50 minThe Flyweight pattern shares what is the same in very many objects.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Few heavy objects, many light ones, and what is passed between them.
Operations
Plant four trees
The factory loads a kind once and hands out the same object afterwards.
Step 1 of 7
Empty
No trees and no types.
Step 1: Empty
class TreeFactory: def get(self, name): found = self._types.get(name) if found is None: mesh, texture = self._load(name) found = self._types[name] = TreeType(name, mesh, texture) return foundclass Forest: def plant(self, x, y, name, tint): self._trees.append(Tree(x, y, tint, self._factory.get(name)))- Watch
- asked and built
- Result
- 4 trees, 2 loads
built stops growing long before trees does.
In the real world
The same flyweight doing real jobs. Pick one and step through it.
The same 10,000 trees with four different keys.
Step 1 of 4
Kind
| Flyweights | Their memory | |
|---|---|---|
| kind | 3 | 2.1 MB |
| kind, colour | ||
| kind, colour, age | ||
| kind, exact height |
Oak, pine, birch.
Step 1: Kind
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Storing the place in the flyweight
criticalAll trees share it, so the last one that set it wins. With threads it is a race.
Wrongdef draw(self, canvas): canvas.stamp(self.mesh, self.x, self.y)Rightdef draw(self, x, y, canvas): canvas.stamp(self.mesh, x, y)A setter
criticalOne write changes every user.
Wrongtree.type.color = "orange"Righttree.tint = "orange"Going around the factory
majorA second oak appears and nothing complains.
WrongTree(1, 2, TreeType("oak"))RightTree(1, 2, factory.get("oak"))Joining key parts without a separator
majorab + c and a + bc are the same key.
Wrongkey = font + size_textRightkey = (font, size)Building before looking
majorThe object is built at each call and thrown away.
Wrongtypes.setdefault(name, TreeType(name))Rightif name not in types: types[name] = TreeType(name)Comparing boxed numbers
majorSmall values are shared, large ones are not.
Wrongif (orderId == otherId) // IntegerRightif (orderId.equals(otherId))
Interview tips
Before you split
- Take a heap snapshot
- Name n, k and the size of the equal part
- Estimate the saving aloud
Good signs
- The number of flyweights stands still
- No setters
- One place that creates them
Warning signs
- The map grows with the objects
- A flyweight with a position
- A lock on a shared object
In the interview
- Say facts about oaks, facts about this oak
- Calculate 7 GB and 2.34 MB
- Mention that contexts come next