AlgoViz

Flyweight

medium 50 min

The Flyweight pattern shares what is the same in very many objects.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:45

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

forestForesttrees0factoryTreeFactoryasked0built0

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

FlyweightsTheir memory
kind32.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

    critical

    All trees share it, so the last one that set it wins. With threads it is a race.

    Wrong
    def draw(self, canvas):    canvas.stamp(self.mesh, self.x, self.y)
    Right
    def draw(self, x, y, canvas):    canvas.stamp(self.mesh, x, y)
  • A setter

    critical

    One write changes every user.

    Wrong
    tree.type.color = "orange"
    Right
    tree.tint = "orange"
  • Going around the factory

    major

    A second oak appears and nothing complains.

    Wrong
    Tree(1, 2, TreeType("oak"))
    Right
    Tree(1, 2, factory.get("oak"))
  • Joining key parts without a separator

    major

    ab + c and a + bc are the same key.

    Wrong
    key = font + size_text
    Right
    key = (font, size)
  • Building before looking

    major

    The object is built at each call and thrown away.

    Wrong
    types.setdefault(name, TreeType(name))
    Right
    if name not in types:    types[name] = TreeType(name)
  • Comparing boxed numbers

    major

    Small values are shared, large ones are not.

    Wrong
    if (orderId == otherId)   // Integer
    Right
    if (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