creational
Prototype
Create new objects by copying (cloning) an existing object.
Sometimes building an object is slow. It might read from a database, call a service, or parse a large file.
If you need twenty similar objects, doing that work twenty times is wasteful. Most of the result is identical anyway.
Prototype builds the object properly once, then copies it. Copying memory is far cheaper than repeating the original work. You adjust only the few fields that differ.
A photocopier — you don't retype a document for each copy; you duplicate the original.
Key Concepts
1
The class provides a clone() method that returns a copy of itself.
clone()
2
You create one fully built instance and keep it as the prototype. When you need another, you clone it and change what is different.
3
The main decision is shallow versus deep copy. A shallow copy shares the nested objects, so changing one copy changes the others. A deep copy duplicates them too. Getting this wrong causes bugs that look random and are painful to trace.
When to use it
- Creating objects is more expensive than copying
- You need many objects that differ in a few fields
- Avoid complex class hierarchy to vary initial state
Watch out for
- Deep vs Shallow copy — always be explicit. Shallow clone shares references to nested objects.
java
public abstract class Shape implements Cloneable {
public int x, y;
public String color;
public Shape(Shape source) {
this.x = source.x;
this.y = source.y;
this.color = source.color;
}
public abstract Shape clone();
}
public class Circle extends Shape {
public int radius;
public Circle(Circle source) {
super(source);
this.radius = source.radius;
}
public Circle clone() { return new Circle(this); }
}