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

Copy

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

Copy

πŸ” 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

Copy

πŸ” Fix:

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


πŸ”Ή 4. Cloning Objects with Nested Structures

Copy

πŸ” Benefit:

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


πŸ”Ή 5. Storing Prototypes in a Registry

Copy

πŸ” Use Case:

  • A prototype registry lets us create clones dynamically.


πŸ”Ή 6. Prototype with a Factory Method

Copy

πŸ” Benefit:

  • Factory methods allow structured prototype creation.


πŸ”Ή 7. Cloning Objects with Custom Adjustments

Copy

πŸ” Benefit:

  • Allows cloning with modifications.


πŸ”Ή 8. Preventing Cloning (Singleton-Like Behavior)

Copy

πŸ” Use Case:

  • Ensures singleton objects cannot be cloned.


πŸ”Ή 9. Prototype with Class-Level Attributes

Copy

πŸ” Issue:

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


πŸ”Ή 10. Thread-Safe Cloning in a Multi-Threaded Environment

Copy

πŸ” 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