Prototype

November 26, 20269 minutes

A diagram editor has to duplicate shapes it only knows as Shape. Learn how Prototype lets each shape copy itself, why a shallow copy of a group shares its children, and when not to copy at all.

You select a shape in a diagram editor and press Ctrl+D. A copy appears, with the same size, the same colour, the same style. The shape might be a circle, a rectangle, or a whole group of shapes. The duplicate code only knows that it’s holding a shape. So how do you copy something, when you can’t even name what it is? There’s an old answer to that, and it’s called the Prototype pattern.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.

A photocopied form

Say you’ve spent an hour filling in a form, and now you need a second one. You don’t fetch a blank and fill it in again. You photocopy it. Every answer is already there. And the photocopier didn’t need to know what the form was for.

But look closely. The form says, see attached photo. The photocopy says the same, and points at the very same photo. Mark up that photo, and both forms change. The photocopy shared the attachment instead of copying it.

In code, the form is the prototype. The photocopy is the clone. And a copy that shares the photo is a shallow copy.

The photocopy analogy mapped onto code: the filled-in form is the prototype, the photocopy is the clone, and a copy that points at the same photo is a shallow copy. The photocopy analogy mapped onto code: the filled-in form is the prototype, the photocopy is the clone, and a copy that points at the same photo is a shallow copy.
The form, mapped onto the code.

The obvious version: duplicate with instanceof

Here’s the obvious version. A duplicate method checks what kind of shape it was given, and builds a new one of the same kind.

Shape duplicate(Shape s) {
    if (s instanceof Circle c) {
        return new Circle(c.x(), c.y(), c.radius(), c.color());
    } else if (s instanceof Rect r) {
        return new Rect(r.x(), r.y(), r.width(), r.height(), r.color());
    }
    throw new IllegalArgumentException("unknown shape");
}

For a circle, it reads the position, the radius and the colour, and calls the constructor. A rectangle gets the same treatment. With two shapes, that’s fair. It’s explicit, and every line is easy to read.

Why it breaks

Then the team adds a star. Nobody touches duplicate, so duplicating a star throws an exception. Every new shape needs another branch.

Worse, a copy can be wrong with no error at all. The rectangle gains a rotation. duplicate never heard of it, so the copy comes out upright. And the copying code can only read what a shape lets it see. A private field is out of reach.

Knowing how to copy a shape is the shape’s job. Here, it lives in the editor. refactoring.guru makes the same point: copying from outside isn’t always possible, because some fields may be private, and it ties your code to the object’s concrete class.

The key idea: ask the shape to copy itself

So ask the shape to copy itself. Put a copy method on the Shape interface. Each shape knows its own fields, private or not. So each one builds its own twin. That’s the whole idea: the shape is the one place that knows how to make its own twin.

The editor calls copy on whatever is selected, and never names a class. A star works the day it exists.

Sequence: the Editor calls copy() on the selected Shape; the concrete shape (a Circle) builds its own twin with its copy constructor and returns it; the editor never names the class. Sequence: the Editor calls copy() on the selected Shape; the concrete shape (a Circle) builds its own twin with its copy constructor and returns it; the editor never names the class.
The editor never names a class.

The Gang of Four put it this way (Design Patterns, 1994):

“Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.”

Don’t rebuild it. Copy it.

Building it

Start with the interface. A shape can move, and a shape can copy itself.

public interface Shape {
    Shape copy();
    void moveBy(int dx, int dy);
}

A circle implements copy with a copy constructor. It takes another circle, and copies each field across. copy returns a new circle, passing this. The twin is built by the circle’s own code, so private fields are no problem.

public class Circle implements Shape {
    private int x, y, radius;
    private String color;

    // usual constructor, draw() and moveBy() omitted

    public Circle(Circle other) {
        this.x = other.x;
        this.y = other.y;
        this.radius = other.radius;
        this.color = other.color;
    }

    @Override
    public Shape copy() {
        return new Circle(this);
    }
}

The editor shrinks to three lines. Copy the selection, move it a little, and add it to the canvas. It works for a circle, a rectangle, and a star that doesn’t exist yet. The editor never changes.

Shape copy = selected.copy();
copy.moveBy(20, 20);
canvas.add(copy);

And the rotation bug is gone. The rectangle’s own copy constructor copies the rotation, because the rectangle knows it has one.

Shallow or deep

Now the group. A group is a shape that holds a list of shapes. Move the group, and every child moves with it (this is the Composite pattern).

public class Group implements Shape {
    private final List<Shape> children;

    public Group(Group other) {
        this.children = other.children;   // the same list!
    }

    @Override
    public Shape copy() {
        return new Group(this);
    }

    @Override
    public void moveBy(int dx, int dy) {
        for (Shape child : children) {
            child.moveBy(dx, dy);
        }
    }
}

Its copy constructor looks natural. Just take the other group’s children. But that copies the reference to the list, and not the list itself. Duplicate the group, and move the copy. The original moves too, because both groups share one list of children.

Shape twin = group.copy();
twin.moveBy(20, 20);   // the original group moved too
Shallow versus deep copy of a group. Shallow: the original group and the copy both point at one shared list holding two children. Deep: each group has its own list, and the copy's list holds copies of the two children. Shallow versus deep copy of a group. Shallow: the original group and the copy both point at one shared list holding two children. Deep: each group has its own list, and the copy's list holds copies of the two children.
Shallow: one list, two groups. Deep: two lists.

The fix is a deep copy. Make a new list, and ask each child to copy itself.

public Group(Group other) {
    this.children = new ArrayList<>();
    for (Shape child : other.children) {
        this.children.add(child.copy());
    }
}

A group inside a group copies its own children the same way, so the copy goes all the way down. The Gang of Four describe the difference like this: a shallow copy shares the internal references of the original, while a deep copy also clones the components, so the clone and original are fully independent.

Back to the photocopy. A shallow copy is the photocopy with the clip still holding the same photo. A deep copy photographs the photo too.

A rule of thumb: copy what the copy will change. Mutable parts the shape owns get their own copy. Strings and numbers can be shared.

Anatomy

The pattern has three roles. The prototype is the Shape interface. The concrete prototypes are Circle, Rect and Group. And the client is the Editor.

Class diagram of Prototype: the Editor uses the Shape interface (copy, moveBy). Circle, Rect and Group implement Shape; Group holds a list of Shapes. Class diagram of Prototype: the Editor uses the Shape interface (copy, moveBy). Circle, Rect and Group implement Shape; Group holds a list of Shapes.
Three roles: prototype, concrete prototypes, client.

Inside each concrete prototype, you choose how to copy. A copy constructor takes another object of its own type (new Circle(other)). A copy factory is the same idea as a static method (Circle.copyOf(other)). Both work with final fields, and neither throws a checked exception. Joshua Bloch’s Effective Java (Item 13, “Override clone judiciously”) recommends them over clone.

And decide what a copy shares: copy the mutable parts the shape owns, and share the immutable ones.

A registry of prototypes

Here’s a second use. The editor has a palette of ready-made shapes: a warning sticker, a note card. Each one is a shape, set up once. The palette keeps them in a map, by name.

public class ShapePalette {
    private final Map<String, Shape> prototypes = new HashMap<>();

    public void register(String key, Shape prototype) {
        prototypes.put(key, prototype);
    }

    public Shape create(String key) {
        return prototypes.get(key).copy();
    }
}

To make a note card, ask the palette. It looks up the prototype, and hands back a copy of it.

palette.register("note", noteCard);
Shape note = palette.create("note");
Class diagram of a prototype registry: the ShapePalette holds a map of names to Shape prototypes; register adds one, create(key) returns a copy of the prototype stored under that key. Class diagram of a prototype registry: the ShapePalette holds a map of names to Shape prototypes; register adds one, create(key) returns a copy of the prototype stored under that key.
A registry is a map of prototypes.

A new preset is one more registered shape. No new class, and no subclass for each preset. Presets differ only in their fields, like colour, size and text. That’s why copying a configured shape beats writing a class for each one (the Gang of Four list this as a reason to use the pattern: when instances have only a few distinct combinations of state). The GoF call this store a prototype manager.

And sometimes you don’t need to copy at all. If a shape is immutable, like a record, everyone can share one instance.

The mix-up: clone, and the other creational patterns

Now a common mix-up: clone() is the Prototype pattern in Java. It isn’t. The pattern is copying an existing object through an interface.

Cloneable is one awkward way to do it. The Javadoc says the interface does not contain the clone method, so implementing it doesn’t let you clone anything by itself. Object.clone() is protected. It copies fields one for one “as if by assignment”, so it performs a shallow copy, and it declares a checked CloneNotSupportedException.

public class Circle implements Shape, Cloneable {
    // fields, copy() and moveBy() omitted

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

Next to its neighbours:

PatternWhere the new object comes from
Factory Methoda subclass decides which class to create
Abstract Factorya factory decides which family of classes to create
Builderbuilt step by step, from nothing
Prototypecopied from an instance that’s already set up

Prototype starts from an instance that’s already set up, and copies it. (refactoring.guru notes that Factory Method relies on inheritance and needs no initialization step, while Prototype avoids inheritance but needs the clone to be initialized.)

When not to use it

When should you skip it? If objects are cheap and simple to build, new is clearer than a copy method. If they’re immutable, share them. A copy of something that can never change is just a second place to look.

And there’s a cost. Every class needs a copy method, kept in step with its fields. Add a field, and you update the copy. Cycles make deep copies tricky too: if shapes can point at each other in a loop, a naive deep copy never ends (refactoring.guru: “Cloning complex objects that have circular references might be very tricky.”).

Decision: is the object cheap and simple to build? Use new. Is it immutable? Share it. Do you only know its interface? Ask it to copy itself; copy the mutable parts it owns, and watch for cycles. Decision: is the object cheap and simple to build? Use new. Is it immutable? Share it. Do you only know its interface? Ask it to copy itself; copy the mutable parts it owns, and watch for cycles.
Copy only what is worth copying.

Recap

  • When you only know the interface, ask the object to copy itself.
  • A copy constructor is the simplest way.
  • Copy deep enough: a new list, with every child copying itself.
  • A registry is a map of prototypes. clone is one mechanism, not the pattern.
  • Skip all of it for cheap or immutable objects.
Recap chain: ask the object to copy itself, copy the mutable parts it owns, keep presets in a registry. Recap chain: ask the object to copy itself, copy the mutable parts it owns, keep presets in a registry.
Copy it, and copy it deep enough.

Checklist:

  • Do you only know the object’s interface, not its class?
  • Does the interface have a copy() that each class implements?
  • Does every mutable part the object owns get its own copy (a new list, copied children)?
  • Is the object really costly to rebuild, and able to change after copying?
  • Could new, or sharing an immutable instance, do the job instead?

Don’t rebuild it. Copy it, and copy it deep enough.

Related lessons: Composite, Factory Method, Abstract Factory, Builder.

Further reading

  • Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns (1994): Prototype.
  • Joshua Bloch, Effective Java, 3rd ed., Item 13, “Override clone judiciously”.
  • refactoring.guru: Prototype.
  • Object.clone() and Cloneable javadoc.