Skip to main content

Definition

“Prototype pattern lets you produce a copy of an object without knowing anything about its type”
In general: specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
prototype

Explanation

You define a clone() method in a class (or an interface) which returns a copy of the object. The client, which may not know the concrete class, just calls clone() on an existing instance (the prototype) to get a new object. This is useful when creating a new instance is expensive or when dynamic cloning is needed.

Code

In this example, Creator defines the factory method factory_method(), and its subclasses (ConcreteCreator1, ConcreteCreator2) override this method to create specific products (ConcreteProduct1, ConcreteProduct2). The client code uses a creator without knowing the exact product class.
import copy

class Prototype:
    def __init__(self, items):
        self.items = items

    def clone(self):
        return copy.copy(self)

def main():
    original = Prototype([1, 2, 3])
    clone = original.clone()
    print(f"Original items: {original.items}")
    print(f"Cloned items:   {clone.items}")
    print(f"Lists are shared? {original.items is clone.items}")
    clone.items.append(4)
    print("After modifying the clone's list:")
    print(f"Original items: {original.items}")
    print(f"Cloned items:   {clone.items}")

if __name__ == "__main__":
    main()


Analogy

Photocopier machine: you take an original document (prototype) and make copies. You don’t know the document content, just that you get an exact replica. Or cloning real-world objects, like making a 3D print of an object.

Interview Insights

Common uses: When object creation is costly (e.g. heavy initialization) and many similar objects are needed. Also when classes should not be tightly coupled: new objects can be made without knowing class. Used in frameworks with dynamic loading (clone a prototype).
Advantages: Adds flexibility by decoupling object creation from classes. Can add or remove prototypes at runtime.
Disadvantages: Cloning complex objects can be tricky (deep vs shallow copy). Can be overused if simple constructors suffice. Prototype registry can become complex.\