Pass position as extrinsic state

Step 3: Pass position as extrinsic state

A flyweight splits state in two. Intrinsic state is shared and immutable, here the character shape itself. Extrinsic state varies per use and must be supplied by the caller, never stored on the shared object. For a glyph the extrinsic state is where it is drawn: its position.

Implement Glyph.render(position). It returns a string that combines the intrinsic char with the extrinsic position, for example the char, an at-sign, then the position. Crucially it must NOT store position on the glyph. The same shared glyph can be rendered at many positions, so keeping position would corrupt the shared state.

Hints
Starter code
class Glyph:
    def __init__(self, char):
        self.char = char

    def render(self, position):
        """Return a string of the intrinsic char at the extrinsic position.

        TODO: combine char and position without storing position.
        """
        # TODO: return a string built from self.char and position
        pass


class GlyphFactory:
    def __init__(self):
        self._cache = {}

    def get(self, char):
        if char not in self._cache:
            self._cache[char] = Glyph(char)
        return self._cache[char]

    def count(self):
        return len(self._cache)
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.