Problem Statement
Creating new objects by initializing them from scratch can be slow and error-prone, especially when many objects share similar properties. This leads to duplicated code and inconsistent object states when copying manually.
This diagram shows the client requesting a clone from the prototype object, which returns a new cloned object.
### Before Prototype Pattern (manual copy) class Car: def __init__(self, model, color, options): self.model = model self.color = color self.options = options car1 = Car('Sedan', 'Red', ['GPS', 'Sunroof']) # Manual copy car2 = Car(car1.model, car1.color, list(car1.options)) ### After Prototype Pattern (using clone method) import copy class CarPrototype: def __init__(self, model, color, options): self.model = model self.color = color self.options = options def clone(self): return copy.deepcopy(self) car1 = CarPrototype('Sedan', 'Red', ['GPS', 'Sunroof']) car2 = car1.clone()
Prototype pattern in system design?clone method in a prototype interface?public Object clone(); correctly returns a cloned object. Void return types or different method names are incorrect.class Shape {
int x, y;
Shape(int x, int y) { this.x = x; this.y = y; }
Shape clone() { return new Shape(x, y); }
}
Shape original = new Shape(5, 10);
Shape copy = original.clone();
System.out.println(copy.x + "," + copy.y);class Document {
String content;
Document(String content) { this.content = content; }
Document clone() {
Document copy = this;
return copy;
}
}this to copy, so it returns the same object reference, not a new object.Pass the test and this pattern moves unknown