# Purpose
The Prototype allows the creation of new objects by cloning an existing object, known as the prototype, avoiding the need to know the details of how these objects are created.
We have an object with some possible states, we create prototypes of each one and clone them, avoiding having to pass many parameters or knowing what values go in each one.
# Problem
The need to duplicate existing objects, with similar behavior or state, or when direct creation is expensive (in terms of resources or time).
# Solution
-
Object Cloning: Instead of creating an object from scratch, an existing one is cloned which serves as a prototype.
-
Common Cloning Interface: This allows objects to be cloned without coupling the code to the concrete type of the object.
# Structure
# Participants
- Prototype: Interface to clone itself.
- ConcretePrototype: Implements an operation to clone itself.
- Client: Creates a new object by asking a prototype to clone itself.
# When to Use It
-
The classes to instantiate are specified at runtime.
-
Instances of a class can have one of a few states.
-
High creation costs compared to cloning.
-
Similar objects are required.
# Advantages
-
verified
Efficiency: Cloning is more efficient than creating from scratch.
-
verified
Hiding: The client ignores the complexity of construction.
-
verified
Flexibility: Add/remove objects at runtime.
# Disadvantages
-
warning
Complex Cloning: Problems with circular references or deep cloning.
-
warning
Clone Operation: Requires implementing it in all subclasses.
# Example: Graphics System
We develop a system and need to create multiple instances of configurable geometric shapes (circles or rectangles).
Problem
Create shapes efficiently without knowing how they are built, considering that they can be expensive to replicate.
Proposed Solution
We implement a Prototype to clone existing objects. We create the Shape interface, and the Circle and Rectangle classes that know how to clone themselves.
# Java Code
interface Shape {
Shape clone();
}
class Circle implements Shape {
private int radius;
public Circle(int radius) { this.radius = radius; }
@Override
public Circle clone() { return new Circle(this.radius); }
}
class Rectangle implements Shape {
private int width, height;
public Rectangle(int w, int h) { this.width = w; this.height = h; }
@Override
public Rectangle clone() { return new Rectangle(this.width, this.height); }
}
class GraphicTool {
private Shape shape;
public GraphicTool(Shape shape) { this.shape = shape; }
public Shape createShape() { return shape.clone(); }
}
# Conclusions
The use of a Prototype allows creating instances of complex objects efficiently, avoiding the expensive creation from scratch every time.
# Related Patterns
Factory Method
Often used with Prototype to create objects.
Abstract Factory
A factory can store prototypes to clone products.
Composite and Decorator
Designs with these patterns benefit greatly from Prototype.