forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflyweight.py
More file actions
62 lines (49 loc) · 1.77 KB
/
flyweight.py
File metadata and controls
62 lines (49 loc) · 1.77 KB
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
import random
from enum import Enum
CarType = Enum('CarType', 'subcompact compact suv')
class Car:
pool = dict()
def __new__(cls, car_type):
obj = cls.pool.get(car_type, None)
if not obj:
obj = object.__new__(cls)
cls.pool[car_type] = obj
obj.car_type = car_type
return obj
def render(self, color, x, y):
type = self.car_type
msg = f'render a car of type {type} and color {color} at ({x}, {y})'
print(msg)
def main():
rnd = random.Random()
#age_min, age_max = 1, 30 # in years
colors = 'white black silver gray red blue brown beige yellow green'.split()
min_point, max_point = 0, 100
car_counter = 0
for _ in range(10):
c1 = Car(CarType.subcompact)
c1.render(random.choice(colors),
rnd.randint(min_point, max_point),
rnd.randint(min_point, max_point))
car_counter += 1
for _ in range(3):
c2 = Car(CarType.compact)
c2.render(random.choice(colors),
rnd.randint(min_point, max_point),
rnd.randint(min_point, max_point))
car_counter += 1
for _ in range(5):
c3 = Car(CarType.suv)
c3.render(random.choice(colors),
rnd.randint(min_point, max_point),
rnd.randint(min_point, max_point))
car_counter += 1
print(f'cars rendered: {car_counter}')
print(f'cars actually created: {len(Car.pool)}')
c4 = Car(CarType.subcompact)
c5 = Car(CarType.subcompact)
c6 = Car(CarType.suv)
print(f'{id(c4)} == {id(c5)}? {id(c4) == id(c5)}')
print(f'{id(c5)} == {id(c6)}? {id(c5) == id(c6)}')
if __name__ == '__main__':
main()