The Prototype pattern lets you create new objects by copying existing ones instead of creating them from scratch. It’s useful when objects are complex or costly to initialize.
Creating certain objects can take time or use a lot of resources, especially if they have many attributes or dependencies. Rather than rebuilding these objects each time, the Prototype pattern allows you to clone an existing object and modify the copy if needed.
Use this pattern when:
Avoid using this pattern if:
Each object defines a clone()
method that returns a new copy. This method is usually part of a base Prototype
class or interface. In many cases, clone()
uses a deep copy to ensure the new object doesn’t share references with the original.
Think of using a house blueprint. Instead of designing each house from scratch, you copy the blueprint and customize the new house as needed. This saves time and ensures consistency.
Here’s a basic Python implementation:
import copy
from abc import ABC, abstractmethod
class Prototype(ABC):
@abstractmethod
def clone(self):
pass
class Shape(Prototype):
def __init__(self, color: str, position: tuple[int, int]) -> None:
self.color = color
self.position = position
def move(self, dx: int, dy: int) -> None:
x, y = self.position
self.position = (x + dx, y + dy)
def __str__(self) -> str:
return f"Shape(color={self.color}, position={self.position})"
def clone(self):
return copy.deepcopy(self)
original = Shape("blue", (0, 0))
copy1 = original.clone()
copy1.move(5, 10)
print(original) # Shape(color=blue, position=(0, 0))
print(copy1) # Shape(color=blue, position=(5, 10))
In this example:
Shape
implements the Prototype
interface.clone()
returns a deep copy of the object.See the full Python implementation here: Prototype Pattern on GitHub