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.
What the interviewer is probing.
1. "What is Prototype for?" *Probing:* the purpose. *Stalls:* "Copying." *Moves up:* creating an object by copying an existing one, when construction is expensive or the exact class is not known at compile time.
2. "What is the deep versus shallow copy problem?" *Probing:* the critical detail. *Stalls:* "Nothing." *Moves up:* a shallow copy shares referenced objects, so mutating one changes the other — which is the classic bug in a clone implementation.
3. "Why is Java's Cloneable criticised?" *Probing:* the specifics. *Stalls:* "It is fine." *Moves up:* it is a marker interface with no clone method, the contract is loosely specified, and the default is shallow — a copy constructor is preferred.
4. "Where is it genuinely useful?" *Probing:* the practical angle. *Stalls:* "Nowhere." *Moves up:* prototype registries and configuration templates, where objects are expensive to build and then varied slightly.
A photocopier — you don't retype a document for each copy; you duplicate the original.
Key Concepts
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); }
}