CreationalPythonverifiedVerified

Prototype Pattern in Python

Creates new objects by cloning an existing instance, avoiding the cost of building from scratch.

How to Implement the Prototype Pattern in Python

1Step 1: Define the cloneable Prototype using copy

import copy
from dataclasses import dataclass, field


@dataclass
class Shape:
    shape_type: str
    x: int
    y: int
    color: str

    def clone(self) -> "Shape":
        return copy.deepcopy(self)

    def __str__(self) -> str:
        return f"{self.color} {self.shape_type} at ({self.x}, {self.y})"

2Step 2: Implement a group shape with deep cloning

@dataclass
class GroupShape:
    name: str
    shapes: list[Shape] = field(default_factory=list)

    def clone(self) -> "GroupShape":
        return copy.deepcopy(self)

3Step 3: Create a prototype registry for template management

class ShapeRegistry:
    def __init__(self) -> None:
        self._templates: dict[str, Shape] = {}

    def register(self, key: str, shape: Shape) -> None:
        self._templates[key] = shape

    def create(self, key: str) -> Shape:
        template = self._templates.get(key)
        if template is None:
            raise KeyError(f'No template: "{key}"')
        return template.clone()

4Step 4: Clone and customize objects from the registry

registry = ShapeRegistry()
registry.register("red-circle", Shape("circle", 0, 0, "red"))

c1 = registry.create("red-circle")
c2 = registry.create("red-circle")
c2.x = 50
c2.y = 100

print(c1)  # red circle at (0, 0)
print(c2)  # red circle at (50, 100)
print(c1 is c2)  # False

Prototype Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Prototype Pattern in the Real World

Think of a cell dividing through mitosis. Instead of building a new cell from raw amino acids, the existing cell duplicates itself — copying its DNA, organelles, and membrane. The result is a fully functional copy produced far faster than assembling one molecule at a time.