Last active
March 20, 2019 05:15
-
-
Save ferdef/1d332ad70e495806d889994059492f9d 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