Prototype Pattern

Implement a simple Prototype pattern by cloning existing objects.

IntermediateTopic: Object-Oriented Programs
Back

Python Prototype Pattern Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program to implement a simple Prototype pattern

import copy

class Prototype:
    def clone(self):
        return copy.deepcopy(self)


class Document(Prototype):
    def __init__(self, title, content):
        self.title = title
        self.content = content


doc1 = Document("Report", "Content here")
doc2 = doc1.clone()
doc2.title = "Report Copy"

print(doc1.title)
print(doc2.title)
Output
Report
Report Copy

Understanding Prototype Pattern

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents