-
-
Notifications
You must be signed in to change notification settings - Fork 125
/
flyweight_concept.py
62 lines (43 loc) · 1.52 KB
/
flyweight_concept.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# pylint: disable=too-few-public-methods
"The Flyweight Concept"
class IFlyweight():
"Nothing to implement"
class Flyweight(IFlyweight):
"The Concrete Flyweight"
def __init__(self, code: str) -> None:
self.code = code
class FlyweightFactory():
"Creating the FlyweightFactory as a singleton"
_flyweights: dict[str, Flyweight] = {} # Python 3.9
# _flyweights = {} # Python 3.8 or earlier
def __new__(cls):
return cls
@classmethod
def get_flyweight(cls, code: str) -> Flyweight:
"A static method to get a flyweight based on a code"
if not code in cls._flyweights:
cls._flyweights[code] = Flyweight(code)
return cls._flyweights[code]
@classmethod
def get_count(cls) -> int:
"Return the number of flyweights in the cache"
return len(cls._flyweights)
class Context():
"""
An example context that holds references to the flyweights in a
particular order and converts the code to an ascii letter
"""
def __init__(self, codes: str) -> None:
self.codes = list(codes)
def output(self):
"The context specific output that uses flyweights"
ret = ""
for code in self.codes:
ret = ret + FlyweightFactory.get_flyweight(code).code
return ret
# The Client
CONTEXT = Context("abracadabra")
# use flyweights in a context
print(CONTEXT.output())
print(f"abracadabra has {len('abracadabra')} letters")
print(f"FlyweightFactory has {FlyweightFactory.get_count()} flyweights")