Prototype Pattern in Python
Implement a simple Prototype pattern by cloning existing objects.
IntermediateObject-Oriented ProgramsExample 22 of 25
prototype-pattern.py
Run in browser1# Program to implement a simple Prototype pattern23import copy45class Prototype:6 def clone(self):7 return copy.deepcopy(self)89class Document(Prototype):10 def __init__(self, title, content):11 self.title = title12 self.content = content1314doc1 = Document("Report", "Content here")15doc2 = doc1.clone()16doc2.title = "Report Copy"1718print(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.