Skip to content

Commit 30297aa

Browse files
committed
prototype
1 parent 156d3f2 commit 30297aa

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

creational/prototype.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import copy
2+
3+
4+
class Prototype:
5+
def __init__(self):
6+
self._objects = {}
7+
8+
def register(self, name, obj):
9+
self._objects[name] = obj
10+
11+
def unregister(self, name):
12+
del self._objects[name]
13+
14+
def clone(self, name, **kwargs):
15+
clone_obj = copy.deepcopy(self._objects.get(name))
16+
clone_obj.__dict__.update(kwargs)
17+
return clone_obj
18+
19+
20+
def client_prototype(name, obj, **kwargs):
21+
prototype = Prototype()
22+
prototype.register(name, obj)
23+
return prototype.clone(name, **kwargs)
24+
25+
26+
# example #
27+
28+
class Person:
29+
def __init__(self, name, age):
30+
self.name = name
31+
self.age = age
32+
33+
34+
p = Person('mahdi', 20)
35+
p_clone = client_prototype('p', p, age=10)
36+
print(p.__dict__)
37+
print(p_clone.__dict__)

0 commit comments

Comments
 (0)