Prototype design pattern
Himanshu K
Dynamic Engineering Leader | Driving Team Success and Technical Innovation | Engineering Manager at Accenture | Ex- QBurst, Flipkart, Minjar, Msrit
The Prototype design pattern is a creational design pattern that allows you to create new objects by copying an existing object, known as the prototype, rather than creating new instances from scratch. This pattern involves creating clone objects, thereby reducing the need for subclassing. It is useful when the construction of a new object is more efficient by copying an existing object rather than creating it anew.
Key Components:
Advantages of Prototype Pattern:
Disadvantages of Prototype Pattern:
领英推荐
Real-Life Example:
Consider a scenario where you have a graphic design tool like Adobe Illustrator. When creating a new graphic object (e.g., a shape, a text box), instead of starting from scratch and defining all properties and attributes, you can clone an existing object that closely resembles the one you want to create. For instance, if you have a circle with specific attributes (e.g., radius, color, position), you can clone it to create another circle with similar attributes but perhaps a different color or position.
Implementation:
from copy import deepcopy
class GraphicObject:
def clone(self):
pass
class Circle(GraphicObject):
def __init__(self, x, y, radius, color):
self.x = x
self.y = y
self.radius = radius
self.color = color
def clone(self):
# Use deepcopy to create a deep copy of the object
return deepcopy(self)
class Textbox(GraphicObject):
def __init__(self, x, y, width, height, text):
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
def clone(self):
# Use deepcopy to create a deep copy of the object
return deepcopy(self)
# Client
if __name__ == "__main__":
# Create prototype instances
circle_prototype = Circle(100, 100, 50, "blue")
textbox_prototype = Textbox(200, 200, 100, 50, "Hello")
# Clone circle
cloned_circle = circle_prototype.clone()
print("Cloned Circle - x:", cloned_circle.x, "y:", cloned_circle.y, "radius:", cloned_circle.radius, "color:", cloned_circle.color)
# Clone textbox
cloned_textbox = textbox_prototype.clone()
print("Cloned Textbox - x:", cloned_textbox.x, "y:", cloned_textbox.y, "width:", cloned_textbox.width, "height:", cloned_textbox.height, "text:", cloned_textbox.text)
In this example:
This real-life example demonstrates how the Prototype pattern can be used in a graphic design tool to create new graphic objects by cloning existing ones, thereby reducing the need for defining all attributes from scratch.