Creational Clone

Prototype

Prototype creates new objects by copying an existing instance rather than instantiating a class directly, so an object can be duplicated without the copying code knowing its concrete type.

Complexity
Popularity

Problem

A drawing app builds shapes at runtime - a `Circle` placed and dragged into position, recolored, resized. Producing a near-identical copy by calling `new Circle(x, y, color, radius)` means the caller has to know every constructor argument and re-read the original's current field values one by one, which gets brittle the moment a subclass like `Rectangle` adds its own fields the caller doesn't know about.

It gets worse for code that only holds the shape through a common `Shape` reference: it has no way to call `new Circle(...)` or `new Rectangle(...)` on it at all - it doesn't know, and shouldn't need to know, which concrete subclass it's holding.

Solution

Give every shape a `clone()` method it implements on itself, declared through the shared `Shape` interface. Because the method lives inside the class being copied, `Circle` and `Rectangle` each know exactly which fields they carry and copy themselves accordingly, without the caller enumerating constructor arguments by hand.

Calling code never constructs anything with `new` - it just calls `.clone()` on whatever `Shape` it's holding, and gets back an independent copy of the same concrete type (a `Circle` stays a `Circle`), with no need to know what that type is.

When to Use

  • Reach for it when code holds objects only through a common interface and has to duplicate them without ever knowing their concrete class.
  • Reach for it when building a new instance from scratch is measurably more expensive than copying an already-configured one.
  • Reach for it when you're maintaining a growing set of subclasses that differ only in preset field values - a library of cloneable prototypes replaces that hierarchy.

Real-World Examples

  • **`structuredClone()` in browsers and Node.js** - a built-in deep-clone operation that duplicates arbitrary objects, including nested structures, without external libraries.
  • **Java's `Object.clone()` and `Cloneable` interface** - a built-in language-level protocol for objects to define their own shallow or deep copy behavior.
  • **Unity/Unreal prefab and blueprint instantiation** - spawning a game object from a preconfigured template copies a fully set-up prototype rather than rebuilding its components from scratch each time.