Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Singleton Method - Python Design Patterns
Next article icon

Prototype Method Design Pattern in Python

Last Updated : 22 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Prototype Method Design Pattern in Python enables the creation of new objects by cloning existing ones, promoting efficient object creation and reducing overhead. This pattern is particularly useful when the cost of creating a new object is high and when an object's initial state or configuration is complex.

  • By utilizing cloning, developers can streamline object creation, ensuring that new instances are created with the same properties and behaviors as the prototype, while also allowing for easy customization and modification.
  • This article explores the implementation and benefits of the Prototype Method Design Pattern in Python.

Suppose a user creates a document with a specific layout, fonts, and styling, and wishes to create similar documents with slight modifications.

Instead of starting from scratch each time, the user can use the Prototype pattern. The original document becomes the prototype, and new documents are created by cloning this prototype. This approach ensures that the new documents inherit the structure and styling of the original document while allowing for customization.

Prototype-Method-Design-Pattern-in-Python

Important Topics for Prototype Method Design Pattern in Python

  • Components of Prototype Design Pattern
  • Prototype Design Pattern example in Java
  • When to use the Prototype Design Pattern 
  • When not to use the Prototype Design Pattern 

Components of Prototype Design Pattern

The Prototype Design Pattern's components include the prototype interface or abstract class, concrete prototypes and the client code, and the clone method specifying cloning behavior. These components work together to enable the creation of new objects by copying existing ones.

PrototypeComponentdrawio-(2)

1. Prototype Interface or Abstract Class

The Prototype Interface or Abstract Class declares the method(s) for cloning an object. It defines the common interface that concrete prototypes must implement, ensuring that all prototypes can be cloned in a consistent manner.

  • The main role is to provide a blueprint for creating new objects by specifying the cloning contract.
  • It declares the clone method, which concrete prototypes implement to produce copies of themselves.

2. Concrete Prototype

The Concrete Prototype is a class that implements the prototype interface or extends the abstract class. It's the class representing a specific type of object that you want to clone.

  • It defines the details of how the cloning process should be carried out for instances of that class.
  • Implements the clone method declared in the prototype interface, providing the cloning logic specific to the class.

3. Client

The Client is the code or module that requests the creation of new objects by interacting with the prototype. It initiates the cloning process without being aware of the concrete classes involved.

4. Clone Method

The Clone Method is declared in the prototype interface or abstract class. It specifies how an object should be copied or cloned. Concrete prototypes implement this method to define their unique cloning behavior. It Describes how the object's internal state should be duplicated to create a new, independent instance.

Prototype Design Pattern example in Python

In a video game, different types of enemies need to be created with similar initial attributes but slight variations. Creating each enemy from scratch every time it is needed can be inefficient, especially if the enemies share many common attributes. The challenge is to efficiently create these enemies while allowing for easy customization.

How Prototype Design Pattern helps to solve this problem?

Using the Prototype Design Pattern, we can create a prototype of each type of enemy and then clone these prototypes to create new enemies. This approach reduces the overhead of creating each enemy from scratch and ensures that new enemies start with the same attributes as the prototype. Customization can be applied to each cloned enemy as needed.

proto
Class Diagram of Prototype Method Design Pattern in Python

1. Prototype Interface

Python
from abc import ABC, abstractmethod
import copy

class Prototype(ABC):
    @abstractmethod
    def clone(self):
        pass


2. Concrete Prototype (Enemy Prototype)

Python
class EnemyPrototype(Prototype):
    def __init__(self, name, health, attack_power):
        self.name = name
        self.health = health
        self.attack_power = attack_power

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

    def __str__(self):
        return f"Enemy(name={self.name}, health={self.health}, attack_power={self.attack_power})"


3. Client

Python
def client_code(prototype: Prototype):
    prototype_clone = prototype.clone()
    print("Cloned enemy:", prototype_clone)
    # Customizing the cloned enemy
    prototype_clone.health += 10
    prototype_clone.attack_power += 5
    print("Customized cloned enemy:", prototype_clone)


4. Complete code for the above example

Python
from abc import ABC, abstractmethod
import copy

class Prototype(ABC):
    @abstractmethod
    def clone(self):
        pass

class EnemyPrototype(Prototype):
    def __init__(self, name, health, attack_power):
        self.name = name
        self.health = health
        self.attack_power = attack_power

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

    def __str__(self):
        return f"Enemy(name={self.name}, health={self.health}, attack_power={self.attack_power})"

def client_code(prototype: Prototype):
    prototype_clone = prototype.clone()
    print("Cloned enemy:", prototype_clone)
    # Customizing the cloned enemy
    prototype_clone.health += 10
    prototype_clone.attack_power += 5
    print("Customized cloned enemy:", prototype_clone)

if __name__ == "__main__":
    # Creating a prototype for a basic enemy
    basic_enemy_prototype = EnemyPrototype("Goblin", 100, 15)
    print("Original enemy:", basic_enemy_prototype)
    
    # Using the prototype to create and customize new enemies
    client_code(basic_enemy_prototype)

Output
Original enemy: Enemy(name=Goblin, health=100, attack_power=15)
Cloned enemy: Enemy(name=Goblin, health=100, attack_power=15)
Customized cloned enemy: Enemy(name=Goblin, health=110, attack_power=20)

Explanation

  1. Prototype Interface: Defines the clone method that must be implemented by any class that wants to allow cloning.
  2. Concrete Prototype (EnemyPrototype): Implements the clone method using copy.deepcopy to create a deep copy of the object.
  3. Client: Uses the prototype to create a clone and then customizes the cloned object as needed.

In this example, the EnemyPrototype class is used to create prototypes for different types of enemies. The client_code function clones the prototype and customizes the cloned enemy. This pattern allows efficient creation of new enemies while ensuring they start with the same state as the prototype and can be easily customized afterward.

When to use the Prototype Design Pattern 

  • Creating Objects is Costly:
    • Use the Prototype pattern when creating objects is more expensive or complex than copying existing ones.
    • If object creation involves significant resources, such as database or network calls, and you have a similar object available, cloning can be more efficient.
  • Variations of Objects:
    • Use the Prototype pattern when your system needs to support a variety of objects with slight variations.
    • Instead of creating multiple classes for each variation, you can create prototypes and clone them with modifications.
  • Dynamic Configuration:
    • Use the Prototype pattern when your system requires dynamic configuration and you want to create objects with configurations at runtime.
    • You can prototype a base configuration and clone it, adjusting the properties as needed.
  • Reducing Initialization Overhead:
    • Use the Prototype pattern when you want to reduce the overhead of initializing an object.
    • Creating a clone can be faster than creating an object from scratch, especially when the initialization process is resource-intensive.

When not to use the Prototype Design Pattern 

  • Unique Object Instances:
    • Avoid using the Prototype pattern when your application predominantly deals with unique object instances, and the overhead of implementing the pattern outweighs its benefits.
  • Simple Object Creation:
    • If object creation is simple and does not involve significant resource consumption, and there are no variations of objects, using the Prototype pattern might be unnecessary complexity.
  • Immutable Objects:
    • If your objects are immutable (unchangeable) and do not need variations, the benefits of cloning may not be significant.
    • Immutable objects are often safely shared without the need for cloning.
  • Clear Object Creation Process:
    • If your system has a clear and straightforward object creation process that is easy to understand and manage, introducing the Prototype pattern may add unnecessary complexity.
  • Limited Object Variations:
    • If there are only a few variations of objects, and creating subclasses or instances with specific configurations is manageable, the Prototype pattern might be overkill.
       

Next Article
Singleton Method - Python Design Patterns

C

chaudhary_19
Improve
Article Tags :
  • Python
  • python-design-pattern
Practice Tags :
  • python

Similar Reads

    Python Design Patterns Tutorial
    Design patterns in Python are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best pra
    7 min read

    Creational Software Design Patterns in Python

    Factory Method - Python Design Patterns
    Factory Method is a Creational Design Pattern that allows an interface or a class to create an object, but lets subclasses decide which class or object to instantiate. Using the Factory method, we have the best ways to create an object. Here, objects are created without exposing the logic to the cli
    4 min read
    Abstract Factory Method - Python Design Patterns
    Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects. It provides a way to encapsulate a group
    4 min read
    Builder Method - Python Design Patterns
    Builder Method is a Creation Design Pattern which aims to "Separate the construction of a complex object from its representation so that the same construction process can create different representations." It allows you to construct complex objects step by step. Here using the same construction code
    5 min read
    Prototype Method Design Pattern in Python
    The Prototype Method Design Pattern in Python enables the creation of new objects by cloning existing ones, promoting efficient object creation and reducing overhead. This pattern is particularly useful when the cost of creating a new object is high and when an object's initial state or configuratio
    6 min read
    Singleton Method - Python Design Patterns
    Prerequisite: Singleton Design pattern | IntroductionWhat is Singleton Method in PythonSingleton Method is a type of Creational Design pattern and is one of the simplest design patterns available to us. It is a way to provide one and only one object of a particular type. It involves only one class t
    5 min read

    Structural Software Design Patterns in Python

    Adapter Method - Python Design Patterns
    Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to cre
    4 min read
    Bridge Method - Python Design Patterns
    The bridge method is a Structural Design Pattern that allows us to separate the Implementation Specific Abstractions and Implementation Independent Abstractions from each other and can be developed considering as single entities.The bridge Method is always considered as one of the best methods to or
    5 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences