Created
October 12, 2018 12:43
-
-
Save ZoranPandovski/e071e42625dcd224e14c2588208f897b to your computer and use it in GitHub Desktop.
Prototype design pattern in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Prototype(object): | |
value = 'default' | |
def clone(self, **attrs): | |
"""Clone a prototype and update dictionary""" | |
obj = self.__class__() | |
obj.__dict__.update(attrs) | |
return obj | |
class PrototypeDispatcher(object): | |
def __init__(self): | |
self._objects = {} | |
def get_objects(self): | |
"""Get all objects""" | |
return self._objects | |
def register_object(self, name, obj): | |
"""Register an object""" | |
self._objects[name] = obj | |
def unregister_object(self, name): | |
"""Unregister an object""" | |
del self._objects[name] | |
if __name__ == '__main__': | |
dispatcher = PrototypeDispatcher() | |
prototype = Prototype() | |
obj1 = prototype.clone() | |
obj2 = prototype.clone(value='Obj 2', category='a') | |
obj3 = prototype.clone(value='Obj 3', is_checked=True) | |
dispatcher.register_object('default', obj1) | |
dispatcher.register_object('object2', obj2) | |
dispatcher.register_object('object3', obj3) | |
#print objects | |
for k,v in dispatcher.get_objects().items(): | |
print(k + ':' + v.value) | |
#OUTPUT | |
#default:default | |
#object2:Obj 2 | |
#object3:Obj 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment