The Prototype pattern is categorized as a creational design pattern, and its essence lies in the creation of new objects by duplicating an already existing object, referred to as the prototype. This particular pattern proves advantageous in scenarios where the process of creating an object is more intricate or resource-intensive compared to replicating an already established one. In Python, you can implement the Prototype pattern using the copy module or by defining a clone method in your classes.
Here’s a simple example in Python to illustrate the Prototype pattern:
import copy
# Prototype class
class Prototype:
def clone(self):
# Use the copy module to create a shallow copy of the object
return copy.copy(self)
# Concrete prototype class
class Person(Prototype):
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"{self.name}, {self.age} years old")
# Client code
if __name__ == "__main__":
# Create a prototype instance
original_person = Person(name="John", age=30)
# To make new instances, clone the prototype
person1 = original_person.clone()
person2 = original_person.clone()
# Modify the cloned instances
person1.name = "Jane"
person2.age = 25
# Display the original and cloned instances
original_person.display() # Output: John, 30 years old
person1.display() # Output: Jane, 30 years old
person2.display() # Output: John, 25 years old
In this example:
- Prototype is an abstract class with a clone method. The clone method uses the copy module to create a shallow copy of the object.
- Person is a concrete prototype class that inherits from Prototype. It has attributes like name and age and a method display to print the person’s information.
- The client code creates an instance of the Person class as the original prototype. It then clones the prototype to create new instances (person1 and person2). Modifying the cloned instances doesn’t affect the original prototype.
This pattern is useful when you want to create objects with similar properties but don’t want to go through the entire initialization process. It helps in achieving a balance between performance and flexibility in object creation.