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"""Document Template System using Prototype pattern with deep cloning."""
import copy
import uuid
from dataclasses import dataclass, field
# [step] Define deeply-cloneable document components
@dataclass
class FontStyle:
family: str
size: int
weight: int
color: str
def clone(self) -> "FontStyle":
return copy.deepcopy(self)
@dataclass
class Margin:
top: int
right: int
bottom: int
left: int
def clone(self) -> "Margin":
return copy.deepcopy(self)
@dataclass
class Section:
heading: str
content: str
font: FontStyle
margin: Margin
subsections: list["Section"] = field(default_factory=list)
def clone(self) -> "Section":
return copy.deepcopy(self)
@dataclass
class Document:
title: str
author: str
tags: list[str]
sections: list[Section]
header_font: FontStyle
body_font: FontStyle
page_margin: Margin
id: str = field(default_factory=lambda: str(uuid.uuid4()))
def clone(self) -> "Document":
cloned = copy.deepcopy(self)
cloned.id = str(uuid.uuid4()) # New unique ID for each clone
return cloned
# [step] Build the template registry with predefined templates
class TemplateRegistry:
def __init__(self) -> None:
self._templates: dict[str, Document] = {}
def register(self, name: str, template: Document) -> None:
self._templates[name] = template
def create(self, name: str) -> Document:
template = self._templates.get(name)
if template is None:
available = ", ".join(self._templates)
raise KeyError(f'Template "{name}" not found. Available: {available}')
return template.clone()
def list_templates(self) -> list[str]:
return list(self._templates)
# [step] Register templates and create documents from them
registry = TemplateRegistry()
serif = FontStyle("Georgia", 12, 400, "#333")
margin = Margin(72, 72, 72, 72)
registry.register(
"report",
Document(
title="Untitled Report",
author="",
tags=["report"],
sections=[
Section("Executive Summary", "", serif.clone(), margin.clone()),
Section("Findings", "", serif.clone(), margin.clone(), [
Section("Data Analysis", "", serif.clone(), margin.clone()),
]),
Section("Recommendations", "", serif.clone(), margin.clone()),
],
header_font=FontStyle("Georgia", 24, 700, "#111"),
body_font=serif,
page_margin=margin,
),
)
report = registry.create("report")
report.title = "Q4 Performance Review"
report.author = "Alice Chen"
print(f"{report.title} by {report.author} (id={report.id})")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.”