Prototype Pattern is another creational pattern that clones objects as per the prototype. Basically it lets you make copies of existing object.
Prototyping is important when we creating many similar objects, but this process can be expensive so the solution is ‘Cloning’ instead of making individual objects.
Lets consider an analogy here, we are mass producing Butterscotch birthday cakes, and its easy for us to mass produce this variety as we would require same dough, same dressing for all the cakes. In this case we just need to create the first prototype of the Butterscotch cake and rest will be the clone.
Here is an implementation for prototype pattern. I am using deep copy to make a clone of the object.
import copy class Prototype: def __init__(self): self._objects = {} def register_object(self, name, obj): """Registering Objects """ self._objects[name] = obj def unregister_object(self, name): """ Unregistering Objects """ del self._objects[name] def clone(self, name, **attr): """ Clone a registered object and update its value """ obj = copy.deepcopy(self._objects.get(name)) obj.__dict__.update(attr) return obj class Cake: def __init__(self): self.name = 'Butterscotch Birthday Cake' self.icing = 'Vanilla and Butterscotch' self.weight = '1 kg' def __str__(self): return '{} | {} | {}'.format(self.name, self.icing, self.weight) cake = Cake() prototype = Prototype() prototype.register_object('Butterscotch',cake) cake_1 = prototype.clone('Butterscotch') print(cake_1) >> Butterscotch Birthday Cake | Vanilla and Butterscotch | 1 kg
This is the last in Creational Patterns, next we will explore the Structural Patterns. Hope this was useful, Happy coding.