66
77class Prototype :
88
9+ value = 'default'
10+
11+ def clone (self , ** attrs ):
12+ """Clone a prototype and update inner attributes dictionary"""
13+ obj = copy .deepcopy (self )
14+ obj .__dict__ .update (attrs )
15+ return obj
16+
17+
18+ class PrototypeDispatcher :
19+
920 def __init__ (self ):
1021 self ._objects = {}
1122
23+ def get_objects (self ):
24+ """Get all objects"""
25+ return self ._objects
26+
1227 def register_object (self , name , obj ):
1328 """Register an object"""
1429 self ._objects [name ] = obj
@@ -17,34 +32,21 @@ def unregister_object(self, name):
1732 """Unregister an object"""
1833 del self ._objects [name ]
1934
20- def clone (self , name , ** attr ):
21- """Clone a registered object and update inner attributes dictionary"""
22- obj = copy .deepcopy (self ._objects .get (name ))
23- obj .__dict__ .update (attr )
24- return obj
25-
26-
27- class A :
28- def __init__ (self ):
29- self .x = 3
30- self .y = 8
31- self .z = 15
32- self .garbage = [38 , 11 , 19 ]
33-
34- def __str__ (self ):
35- return '{} {} {} {}' .format (self .x , self .y , self .z , self .garbage )
36-
3735
3836def main ():
39- a = A ()
37+ dispatcher = PrototypeDispatcher ()
4038 prototype = Prototype ()
41- prototype .register_object ('objecta' , a )
42- b = prototype .clone ('objecta' )
43- c = prototype .clone ('objecta' , x = 1 , y = 2 , garbage = [88 , 1 ])
44- print ([str (i ) for i in (a , b , c )])
39+
40+ d = prototype .clone ()
41+ a = prototype .clone (value = 'a-value' , category = 'a' )
42+ b = prototype .clone (value = 'b-value' , is_checked = True )
43+ dispatcher .register_object ('objecta' , a )
44+ dispatcher .register_object ('objectb' , b )
45+ dispatcher .register_object ('default' , d )
46+ print ([{n : p .value } for n , p in dispatcher .get_objects ().items ()])
4547
4648if __name__ == '__main__' :
4749 main ()
4850
4951### OUTPUT ###
50- # ['3 8 15 [38, 11, 19]', '3 8 15 [38, 11, 19]', '1 2 15 [88, 1]' ]
52+ # [{'objectb': 'b-value'}, {'default': 'default'}, {'objecta': 'a-value'} ]
0 commit comments