The whole point of a flyweight is memory saving: distinct characters get distinct Glyph objects, but repeats cost nothing new. To prove it, expose how many unique glyphs the factory has actually created.
Implement GlyphFactory.count(). It returns the number of distinct glyphs held in the cache. Requesting the same character several times must not increase the count.
Example: after get("a"), get("b"), get("a"), the factory has created two glyphs, so count() returns 2.
class Glyph:
def __init__(self, char):
self.char = char
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 how many unique glyphs have been created.
TODO: report the size of the flyweight cache.
"""
# TODO: return the number of distinct cached glyphs
passThe editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
The whole point of a flyweight is memory saving: distinct characters get distinct Glyph objects, but repeats cost nothing new. To prove it, expose how many unique glyphs the factory has actually created.
Implement GlyphFactory.count(). It returns the number of distinct glyphs held in the cache. Requesting the same character several times must not increase the count.
Example: after get("a"), get("b"), get("a"), the factory has created two glyphs, so count() returns 2.
Press Run Tests or ββ© to check your solution.