Design Patterns

Pattern 5 of 23, Creational family

Prototype

Create new objects by cloning an existing instance, without depending on its concrete class.

The problem

You want an exact copy of a complex object, but some fields are private and sometimes you only know its interface. Copying field by field from the outside is fragile.

The solution

Delegate the copy to the object itself through a clone() method. The object knows how to copy its own state — including deep copies of collections or nested objects.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. The client asks the prototype itself for a copy.
  2. The object copies its own state, without the client knowing its class.
  3. Client → Red Shape (prototype): clone()
  4. Each clone is a new, independent object.
  5. You customize the clone…
  6. …and the prototype stays untouched (red).

An analogy

Photocopying a form that is already filled in rather than rewriting everything by hand.

When to use it

  • Expensive creation (queries, computation) but cheap copy
  • Preset configurations to duplicate and then tweak
  • Avoid a factory hierarchy that mirrors the class hierarchy

Pros and cons

Pros

  • Clones without coupling to the concrete class
  • Avoids repeating an expensive initialization
  • Lightweight alternative to inheritance for "presets"

Cons

  • Deep copying is tricky (circular references)
  • Shallow vs deep semantics must be documented

Implementations

The same example, written idiomatically in each language.

Prototype in Python

prototype.py 18 lines
import copy


class Shape:
    def __init__(self, color: str, points: list[tuple[int, int]]):
        self.color = color
        self.points = points

    def clone(self) -> "Shape":
        return copy.deepcopy(self)   # deep copy: the list is duplicated


proto = Shape("red", [(0, 0), (10, 10)])
c = proto.clone()
c.color = "blue"
c.points.append((20, 20))

print(proto.color, len(proto.points))   # red 2

Prototype in TypeScript

prototype.ts 18 lines
interface Prototype<T> {
  clone(): T;
}

class Shape implements Prototype<Shape> {
  constructor(public color: string, public points: [number, number][]) {}

  clone(): Shape {
    return new Shape(this.color, structuredClone(this.points));
  }
}

const proto = new Shape("red", [[0, 0], [10, 10]]);
const c = proto.clone();
c.color = "blue";
c.points.push([20, 20]);

console.log(proto.color, proto.points.length); // red 2

Prototype in Java

prototype.java 22 lines
class Shape {
    String color;
    List<int[]> points;

    Shape(String color, List<int[]> points) {
        this.color = color;
        this.points = points;
    }

    // Copy constructor: safer than Object.clone()
    Shape(Shape src) {
        this.color = src.color;
        this.points = new ArrayList<>();
        for (int[] p : src.points) this.points.add(p.clone());
    }

    public Shape copy() { return new Shape(this); }
}

Shape proto = new Shape("red", new ArrayList<>(List.of(new int[]{0, 0})));
Shape c = proto.copy();
c.color = "blue";

Prototype in C#

prototype.cs 9 lines
public record Shape(string Color, IReadOnlyList<(int X, int Y)> Points);

var proto = new Shape("red", [(0, 0), (10, 10)]);

// "with": clone + targeted change (immutable records)
var c = proto with { Color = "blue" };

Console.WriteLine(proto.Color); // red
Console.WriteLine(c.Color);     // blue

Prototype in PHP

prototype.php 23 lines
class Style { public string $font = 'Inter'; }

class Shape
{
    public function __construct(
        public string $color,
        public array $points,
        public Style $style,
    ) {}

    // Called automatically after "clone": deep copy of inner objects
    public function __clone()
    {
        $this->style = clone $this->style;
    }
}

$proto = new Shape('red', [[0, 0], [10, 10]], new Style());
$c = clone $proto;
$c->color = 'blue';
$c->style->font = 'Mono';

echo $proto->style->font; // Inter

Prototype in Go

prototype.go 17 lines
type Shape struct {
    Color  string
    Points [][2]int
}

func (s *Shape) Clone() *Shape {
    pts := make([][2]int, len(s.Points))
    copy(pts, s.Points) // deep copy of the slice
    return &Shape{Color: s.Color, Points: pts}
}

proto := &Shape{Color: "red", Points: [][2]int{{0, 0}, {10, 10}}}
c := proto.Clone()
c.Color = "blue"
c.Points = append(c.Points, [2]int{20, 20})

fmt.Println(proto.Color, len(proto.Points)) // red 2

Frequently asked questions

What is the Prototype design pattern?

Create new objects by cloning an existing instance, without depending on its concrete class. Delegate the copy to the object itself through a clone() method. The object knows how to copy its own state — including deep copies of collections or nested objects.

When should you use the Prototype pattern?

Expensive creation (queries, computation) but cheap copy; Preset configurations to duplicate and then tweak; Avoid a factory hierarchy that mirrors the class hierarchy.

What are the pros and cons of the Prototype pattern?

Pros: Clones without coupling to the concrete class; Avoids repeating an expensive initialization; Lightweight alternative to inheritance for "presets". Cons: Deep copying is tricky (circular references); Shallow vs deep semantics must be documented.