-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflyweightPattern.py
62 lines (46 loc) · 1.47 KB
/
flyweightPattern.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
"""
Use sharing to support large numbers of fine-grained objects
efficiently.
"""
import abc
class FlyweightFactory:
"""
Create and manage flyweight objects.
Ensure that flyweights are shared properly. When a client requests a
flyweight, the FlyweightFactory object supplies an existing instance
or creates one, if none exists.
"""
def __init__(self):
self._flyweights = {}
def get_flyweight(self, key):
try:
flyweight = self._flyweights[key]
except KeyError:
flyweight = ConcreteFlyweight()
self._flyweights[key] = flyweight
return flyweight
class Flyweight(metaclass=abc.ABCMeta):
"""
Declare an interface through which flyweights can receive and act on
extrinsic state.
"""
def __init__(self):
self.intrinsic_state = None
@abc.abstractmethod
def operation(self, extrinsic_state):
pass
class ConcreteFlyweight(Flyweight):
"""
Implement the Flyweight interface and add storage for intrinsic
state, if any. A ConcreteFlyweight object must be sharable. Any
state it stores must be intrinsic; that is, it must be independent
of the ConcreteFlyweight object's context.
"""
def operation(self, extrinsic_state):
pass
def main():
flyweight_factory = FlyweightFactory()
concrete_flyweight = flyweight_factory.get_flyweight("key")
concrete_flyweight.operation(None)
if __name__ == "__main__":
main()