Now assemble a whole run of text. A Document holds a GlyphFactory and turns a string into a list of glyphs, one entry per character, in order. Because it always asks the factory, repeated characters resolve to the very same shared Glyph object.
Implement Document.layout(text). Return a list containing one glyph per character of text, each obtained from self.factory. The list length equals len(text), but the number of UNIQUE glyph objects equals the number of DISTINCT characters. That gap is the memory the flyweight saves.
Example: layout("banana") returns six glyphs, yet only three distinct objects (b, a, n).
class Glyph:
def __init__(self, char):
self.char = char
def render(self, position):
return f"{self.char}@{position}"
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)
class Document:
def __init__(self, factory):
self.factory = factory
def layout(self, text):
"""Return a list of shared glyphs, one per character in text.
TODO: request a glyph from the factory for each character.
"""
# TODO: build and return the list of glyphs using the factory
passThe editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Now assemble a whole run of text. A Document holds a GlyphFactory and turns a string into a list of glyphs, one entry per character, in order. Because it always asks the factory, repeated characters resolve to the very same shared Glyph object.
Implement Document.layout(text). Return a list containing one glyph per character of text, each obtained from self.factory. The list length equals len(text), but the number of UNIQUE glyph objects equals the number of DISTINCT characters. That gap is the memory the flyweight saves.
Example: layout("banana") returns six glyphs, yet only three distinct objects (b, a, n).
Press Run Tests or ββ© to check your solution.