-
-
Save germantellezv/0cc6214dc9e521f1b8e22920a0b22367 to your computer and use it in GitHub Desktop.
Prototype Pattern
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
from copy import deepcopy | |
class Prototype: | |
def __init__(self): | |
self._objects = {} | |
def register_object(self, name, obj): | |
'''Store an object so it can be cloned later''' | |
self._objects[name] = obj | |
def unregister_object(self, name): | |
'''Removes an object from our store''' | |
del self._objects[name] | |
def clone(self, name, **attr): | |
'''clone a registered object and add/replace attributes''' | |
obj = deepcopy(self._objects[name]) | |
obj.__dict__.update(attr) | |
return obj | |
class Test: | |
first_name = None | |
prototype = Prototype() | |
test1 = Test() | |
test1.first_name = "John" | |
print(test1.first_name) | |
prototype.register_object('John', test1) | |
test2 = prototype.clone('John', first_name='Sam') | |
print(test2.first_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment