Skip to content

Commit c6becec

Browse files
authored
Merge pull request faif#371 from yhay81/prototype
Update prototype
2 parents 2bdfe2a + 7c3f71f commit c6becec

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

patterns/creational/prototype.py

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,19 @@
2121
Creates new object instances by cloning prototype.
2222
"""
2323

24+
from typing import Any, Dict
2425

25-
class Prototype:
2626

27-
value = "default"
27+
class Prototype:
28+
def __init__(self, value: str = "default", **attrs: Any) -> None:
29+
self.value = value
30+
self.__dict__.update(attrs)
2831

29-
def clone(self, **attrs):
32+
def clone(self, **attrs: Any) -> None:
3033
"""Clone a prototype and update inner attributes dictionary"""
3134
# Python in Practice, Mark Summerfield
32-
obj = self.__class__()
35+
# copy.deepcopy can be used instead of next line.
36+
obj = self.__class__(**self.__dict__)
3337
obj.__dict__.update(attrs)
3438
return obj
3539

@@ -38,33 +42,36 @@ class PrototypeDispatcher:
3842
def __init__(self):
3943
self._objects = {}
4044

41-
def get_objects(self):
45+
def get_objects(self) -> Dict[str, Prototype]:
4246
"""Get all objects"""
4347
return self._objects
4448

45-
def register_object(self, name, obj):
49+
def register_object(self, name: str, obj: Prototype) -> None:
4650
"""Register an object"""
4751
self._objects[name] = obj
4852

49-
def unregister_object(self, name):
53+
def unregister_object(self, name: str) -> None:
5054
"""Unregister an object"""
5155
del self._objects[name]
5256

5357

54-
def main():
58+
def main() -> None:
5559
"""
5660
>>> dispatcher = PrototypeDispatcher()
5761
>>> prototype = Prototype()
5862
5963
>>> d = prototype.clone()
6064
>>> a = prototype.clone(value='a-value', category='a')
61-
>>> b = prototype.clone(value='b-value', is_checked=True)
65+
>>> b = a.clone(value='b-value', is_checked=True)
6266
>>> dispatcher.register_object('objecta', a)
6367
>>> dispatcher.register_object('objectb', b)
6468
>>> dispatcher.register_object('default', d)
6569
6670
>>> [{n: p.value} for n, p in dispatcher.get_objects().items()]
6771
[{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}]
72+
73+
>>> print(b.category, b.is_checked)
74+
a True
6875
"""
6976

7077

0 commit comments

Comments
 (0)