Prototype Pattern in Python
Prototype avoids rebuilding an object from scratch when copying and adjusting it is simpler.
What is Prototype Pattern?
Prototype avoids rebuilding an object from scratch when copying and adjusting it is simpler.
Create new objects by copying an existing configured object.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example code
main.py
from copy import copy
# Prototype: clone an existing configured object.
class Document:
def __init__(self, status):
self.status = status
def clone(self):
# Return a shallow copy of this configured object.
return copy(self)
draft = Document("Draft")
published = draft.clone()
published.status = "Published"
print(draft.status)
print(published.status)
Expected output
Draft
Published
How it works
copy creates an independent clone whose state can change without altering the prototype.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.