Skip to content

Commit ddd5f86

Browse files
committed
add Flyweight pattern
1 parent a664ecc commit ddd5f86

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

flyweight/Flyweight.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#
2+
# Python Design Patterns: Flyweight
3+
# Author: Jakub Vojvoda [github.com/JakubVojvoda]
4+
# 2016
5+
#
6+
# Source code is licensed under MIT License
7+
# (for more details see LICENSE)
8+
#
9+
10+
import sys
11+
12+
#
13+
# Flyweight
14+
# declares an interface through which flyweights can receive
15+
# and act on extrinsic state
16+
#
17+
class Flyweight:
18+
def operation(self):
19+
pass
20+
21+
#
22+
# UnsharedConcreteFlyweight
23+
# not all subclasses need to be shared
24+
#
25+
class UnsharedConcreteFlyweight(Flyweight):
26+
def __init__(self, state):
27+
Flyweight.__init__(self)
28+
self._state = state
29+
30+
def operation(self):
31+
print("Unshared Flyweight with state " + str(self._state))
32+
33+
#
34+
# ConcreteFlyweight
35+
# implements the Flyweight interface and adds storage
36+
# for intrinsic state
37+
#
38+
class ConcreteFlyweight(Flyweight):
39+
def __init__(self, state):
40+
Flyweight.__init__(self)
41+
self._state = state
42+
43+
def operation(self):
44+
print("Concrete Flyweight with state " + str(self._state))
45+
46+
#
47+
# FlyweightFactory
48+
# creates and manages flyweight objects and ensures
49+
# that flyweights are shared properly
50+
#
51+
class FlyweightFactory:
52+
def __init__(self):
53+
self._flies = {}
54+
55+
def getFlyweight(self, key):
56+
if (self._flies.get(key) is not None):
57+
return self._flies.get(key)
58+
59+
self._flies[key] = ConcreteFlyweight(key)
60+
return self._flies.get(key)
61+
62+
63+
if __name__ == "__main__":
64+
factory = FlyweightFactory()
65+
66+
factory.getFlyweight(1).operation()
67+
factory.getFlyweight(2).operation()

0 commit comments

Comments
 (0)