The Flyweight pattern shares a single immutable object across many uses instead of allocating a fresh one every time. Here the shared object is a Glyph, the drawable shape of a single character. A page of text may show the letter "a" a thousand times, but every one of those can point at the exact same Glyph in memory.
Implement GlyphFactory.get(char). The first time a character is requested, create a Glyph and store it in the internal cache dict. Every later request for that same character must return the identical cached object, not a new equal one.
Use the identity operator is to reason about "same object". Two calls to get with the same character must satisfy: get("a") is get("a").
class Glyph:
def __init__(self, char):
self.char = char
class GlyphFactory:
def __init__(self):
self._cache = {}
def get(self, char):
"""Return a shared Glyph for char, reusing the cached instance.
TODO: implement the flyweight cache lookup.
"""
# TODO: return the cached Glyph for char, creating it only once
passThe editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
The Flyweight pattern shares a single immutable object across many uses instead of allocating a fresh one every time. Here the shared object is a Glyph, the drawable shape of a single character. A page of text may show the letter "a" a thousand times, but every one of those can point at the exact same Glyph in memory.
Implement GlyphFactory.get(char). The first time a character is requested, create a Glyph and store it in the internal cache dict. Every later request for that same character must return the identical cached object, not a new equal one.
Use the identity operator is to reason about "same object". Two calls to get with the same character must satisfy: get("a") is get("a").
Press Run Tests or ββ© to check your solution.