Prototype Pattern

The Prototype pattern is a creational design pattern that allows you to create new objects by copying existing objects, rather than creating new objects from scratch.


import copy

class Prototype:
    def __init__(self):
        self._objects = {}

    def register_object(self, name, obj):
        self._objects[name] = obj

    def unregister_object(self, name):
        del self._objects[name]

    def clone(self, name, **attr):
        obj = copy.deepcopy(self._objects[name])
        obj.__dict__.update(attr)
        return obj

class A:
    pass

a = A()
prototype = Prototype()
prototype.register_object("a", a)
b = prototype.clone("a", a=1, b=2, c=3)

print(a) # <__main__.A object at 0x7f75d9b1fcf8>
print(b.__dict__) # {'a': 1, 'b': 2, 'c': 3}

In this example, the Prototype class is the prototype class that has a dictionary _objects that is used to store the objects that can be cloned. The register_object method is used to add an object to the _objects dictionary, and the unregister_object method is used to remove an object from the dictionary. The clone method is used to create a new object by copying an existing object and updating its attributes with the specified values. The A class is a simple class that is used to demonstrate the prototype pattern. An instance of the A class is created and registered with the prototype. A new object is then cloned from the registered object and its attributes are updated.