Python Prototype Design Pattern

1. Definition

The Prototype Design Pattern creates objects by cloning an existing object, known as the prototype, instead of creating new instances from scratch.

2. Problem Statement

Let's say you are building a game with numerous characters. Each character has many attributes and behaviors. Instantiating and initializing a new character every time can be time-consuming and resource-intensive.

3. Solution

Use the Prototype pattern to clone an existing character (prototype) instead of creating a new one from scratch. This way, you can achieve faster instantiation and can also maintain the state if required.

4. Real-World Use Cases

1. Spawning identical game characters with minimal resource overhead.

2. Creating a backup of the current system state for possible rollbacks.

3. Generating exact copies of complex data structures without direct instantiation.

5. Implementation Steps

1. Define a prototype interface that declares a method for cloning itself.

2. Create concrete classes implementing this prototype interface.

3. Clone the object through the prototype interface whenever a copy is required.

6. Implementation in Python

import copy
# Prototype Interface
class Prototype:
    def clone(self):
        pass
# Concrete Prototype
class GameCharacter(Prototype):
    def __init__(self, name, health, level):
        self.name = name
        self.health = health
        self.level = level
    def clone(self):
        # Using the built-in 'copy' module to create a deep copy
        return copy.deepcopy(self)
    def __str__(self):
        return f"Name: {self.name}, Health: {self.health}, Level: {self.level}"
# Client Code
hero_prototype = GameCharacter("Hero", 100, 1)
print(f"Original Hero: {hero_prototype}")
cloned_hero = hero_prototype.clone()
cloned_hero.name = "Cloned Hero"
print(f"Cloned Hero: {cloned_hero}")

Output:

Original Hero: Name: Hero, Health: 100, Level: 1
Cloned Hero: Name: Cloned Hero, Health: 100, Level: 1

Explanation:

1. A Prototype interface is defined, which mandates a clone method.

2. GameCharacter is a concrete class implementing this prototype, holding attributes like name, health, and level.

3. For cloning, Python's copy module provides a convenient method called deepcopy that creates a full copy of the object.

4. In the client code, an original hero object is instantiated and subsequently cloned. The cloned object is a separate instance and any changes to it don't affect the original.

7. When to use?

The Prototype Pattern is beneficial when:

1. Instances of a class can have only a few different combinations of states. It's more practical to install a corresponding number of prototypes and clone them.

2. Creating a new instance of a class is more expensive (in terms of resources/time) than copying an existing one.

3. Objects are required to be independent of their creation and representation classes.


Comments