# PrototypeA 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.

{{< lesson-video youtube="cXhw2JRHKUI" title="Prototype" >}}

## 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**.

```mermaid {alt="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." caption="The form, mapped onto the code."}
flowchart LR
  A["the filled-in form"] --> A2["prototype"]
  B["the photocopy"] --> B2["clone"]
  C["the same photo"] --> C2["shallow copy"]
  class A2 c6
  class B2 good
  class C2 bad
```

## 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.

```java
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.

```mermaid {alt="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." caption="The editor never names a class."}
sequenceDiagram
  participant E as Editor
  participant S as Shape (a Circle)
  E->>S: copy()
  Note over S: new Circle(this)
  S-->>E: the twin
  E->>S: moveBy(20, 20) on the twin
```

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.

```java
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.

```java
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.

```java
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](/patterns/composite-pattern/) pattern).

```java
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.

```java
Shape twin = group.copy();
twin.moveBy(20, 20);   // the original group moved too
```

```mermaid {alt="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." caption="Shallow: one list, two groups. Deep: two lists."}
flowchart LR
  subgraph SH["Shallow: shared list"]
    direction TB
    G1["group"] --> L["one list"]
    G2["copy"] --> L
    L --> K1["child A"]
    L --> K2["child B"]
  end
  subgraph DP["Deep: own list"]
    direction TB
    H1["group"] --> M1["list"]
    H2["copy"] --> M2["its own list"]
    M1 --> J1["child A"]
    M1 --> J2["child B"]
    M2 --> J3["A copy"]
    M2 --> J4["B copy"]
  end
  SH ~~~ DP
  class G1,G2 bad
  class L bad
  class H1 c6
  class H2,M2,J3,J4 good
```

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

```java
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`.

```mermaid {alt="Class diagram of Prototype: the Editor uses the Shape interface (copy, moveBy). Circle, Rect and Group implement Shape; Group holds a list of Shapes." caption="Three roles: prototype, concrete prototypes, client."}
classDiagram
  class Editor
  class Shape {
    <<interface>>
    +copy() Shape
    +moveBy(dx, dy)
  }
  class Circle
  class Rect
  class Group {
    -children: List~Shape~
  }
  Editor --> Shape : uses
  Shape <|.. Circle
  Shape <|.. Rect
  Shape <|.. Group
  Group o--> Shape : holds many
```

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.

```java
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.

```java
palette.register("note", noteCard);
Shape note = palette.create("note");
```

```mermaid {alt="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." caption="A registry is a map of prototypes."}
classDiagram
  class ShapePalette {
    -prototypes: Map~String, Shape~
    +register(key, prototype)
    +create(key) Shape
  }
  class Shape {
    <<interface>>
    +copy() Shape
  }
  ShapePalette o--> Shape : prototypes
  ShapePalette ..> Shape : create returns a copy
```

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`.

```java
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:

| Pattern | Where the new object comes from |
|---|---|
| [Factory Method](/patterns/factory-method-pattern/) | a subclass decides which class to create |
| [Abstract Factory](/patterns/abstract-factory-pattern/) | a factory decides which family of classes to create |
| [Builder](/patterns/builder-pattern/) | built step by step, from nothing |
| Prototype | copied 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.").

```mermaid {alt="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." caption="Copy only what is worth copying."}
flowchart TD
  Q1{"Cheap and simple to build?"} -->|yes| A1["use new"]
  Q1 -->|no| Q2{"Immutable?"}
  Q2 -->|yes| A2["share one instance"]
  Q2 -->|no| Q3{"Need a copy through an interface?"}
  Q3 -->|no| A3["a plain constructor is fine"]
  Q3 -->|yes| A4["copy(): deep enough, watch cycles"]
  class A4 good
  class A1,A2,A3 muted
```

## 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.

```mermaid {alt="Recap chain: ask the object to copy itself, copy the mutable parts it owns, keep presets in a registry." caption="Copy it, and copy it deep enough."}
flowchart LR
  A["ask the object to copy itself"] --> B["copy what the copy will change"] --> C["presets in a registry"]
  class A c6
  class B good
  class C c5
```

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](/patterns/composite-pattern/), [Factory Method](/patterns/factory-method-pattern/),
[Abstract Factory](/patterns/abstract-factory-pattern/), [Builder](/patterns/builder-pattern/).

## 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](https://refactoring.guru/design-patterns/prototype).
- [`Object.clone()`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Object.html#clone()) and
  [`Cloneable`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Cloneable.html) javadoc.
