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.
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)The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
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.
Press Run Tests or ββ© to check your solution.