Prototype Pattern in Python

Implement a simple Prototype pattern by cloning existing objects.

IntermediateObject-Oriented ProgramsExample 22 of 25
prototype-pattern.py
Run in browser
1# Program to implement a simple Prototype pattern
2
3import copy
4
5class Prototype:
6 def clone(self):
7 return copy.deepcopy(self)
8
9class Document(Prototype):
10 def __init__(self, title, content):
11 self.title = title
12 self.content = content
13
14doc1 = Document("Report", "Content here")
15doc2 = doc1.clone()
16doc2.title = "Report Copy"
17
18print(doc1.title)
19print(doc2.title)

Output

Report
Report Copy

What's going on

The base Prototype class offers a 'clone' method that subclasses can reuse to duplicate instances.