Video in progress

Strong Junior 🧭 Design patterns

What is the Prototype pattern, and what traps come with doing it through `clone()` in Java?

Prototype creates a new object by copying an existing sample instead of building it from scratch. clone() in Java makes a shallow copy by default: inner lists and objects stay shared between the two copies.

📖 Answer

When you need Prototype: creating the object is expensive (lots of setup, reading from the database), or you need many objects that differ slightly from one template.

The problem with clone():

class Template implements Cloneable {
    String title;
    List<String> tags = new ArrayList<>();

    @Override
    public Template clone() {
        try { return (Template) super.clone(); }
        catch (CloneNotSupportedException e) { throw new AssertionError(e); }
    }
}

Template a = new Template();
Template b = a.clone();
b.tags.add("yangi");      // a.tags changed too!

super.clone() copies the fields one by one, and tags is a reference, so both objects point to the same list. For a deep copy you need to do copy.tags = new ArrayList<>(tags) inside clone().

Other drawbacks of Cloneable: it's a marker interface, the clone method is protected in Object, it throws a checked exception, and it doesn't work well with final fields.

That's why most people prefer a copy constructor or a static factory: new Template(other) or Template.copyOf(other). With records, withX(...)-style methods are enough.