212. The Prototype Design Pattern

🔹 The Prototype Design Pattern in Python

The Prototype Pattern is a creational design pattern that allows us to clone objects without depending on their classes. Instead of creating a new object from scratch, we copy an existing one.

Here are 10 Python snippets demonstrating object cloning using the Prototype Pattern.


🔹 1. Basic Prototype Pattern

import copy

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

class Person(Prototype):
    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person("Alice", 25)
p2 = p1.clone()

print(p1.name, p1.age)  # Alice 25
print(p2.name, p2.age)  # Alice 25
print(p1 is p2)         # False (Different objects)

🔍 Issue:

  • The cloned object (p2) is a separate instance from p1, but it has the same attributes.


🔹 2. Cloning a List in an Object

🔍 Issue:

  • Cloning with copy.copy() (shallow copy) shares the same list reference.

  • Solution: Use copy.deepcopy() instead.


🔹 3. Deep Copy to Avoid Shared Mutable Objects

🔍 Fix:

  • copy.deepcopy() ensures car1.features and car2.features are separate.


🔹 4. Cloning Objects with Nested Structures

🔍 Benefit:

  • Deep copying ensures that modifications to car2 do not affect car1.


🔹 5. Storing Prototypes in a Registry

🔍 Use Case:

  • A prototype registry lets us create clones dynamically.


🔹 6. Prototype with a Factory Method

🔍 Benefit:

  • Factory methods allow structured prototype creation.


🔹 7. Cloning Objects with Custom Adjustments

🔍 Benefit:

  • Allows cloning with modifications.


🔹 8. Preventing Cloning (Singleton-Like Behavior)

🔍 Use Case:

  • Ensures singleton objects cannot be cloned.


🔹 9. Prototype with Class-Level Attributes

🔍 Issue:

  • Without .copy(), both objects share the same settings reference!


🔹 10. Thread-Safe Cloning in a Multi-Threaded Environment

🔍 Use Case:

  • Avoids race conditions when cloning in multi-threaded applications.


🚀 Summary

Concept

Description

Basic Prototype

Clones an object using copy.deepcopy()

Avoid Shared References

Use deep copy to prevent shared mutable objects

Prototype Registry

Store prototypes and retrieve clones dynamically

Factory Pattern

Combine Prototype with Factory for structured cloning

Custom Adjustments

Clone while modifying attributes dynamically

Prevent Cloning

Restrict cloning in singleton objects

Thread-Safe Cloning

Use locks to avoid race conditions


🚀 Best Practices

✅ Use deep copy to avoid reference-sharing issues. ✅ Store prototypes in a registry for structured access. ✅ Implement clone_with_changes() for dynamic modifications. ✅ Ensure thread safety if cloning in a multi-threaded environment.

Last updated