Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 57 ยท Creational Patterns

Prototype

Learn the Prototype design pattern: create objects by cloning, understand shallow vs deep copies, use a prototype registry and structuredClone.

The Prototype pattern creates new objects by copying an existing one, the prototype, instead of building them from scratch. The client asks the object to clone itself, so it does not need to know the concrete class or repeat an elaborate setup.

Cloning is useful when creation is expensive (a document template that took many steps to configure), when you want many similar objects that differ in a few fields (game enemies, report layouts) or when the code only holds an interface and cannot call a constructor. The central difficulty is what exactly gets copied, which brings us to the most important idea in this lesson: shallow versus deep copies.

Clone, then tweak

Prototype An already configured object.
clone() Returns an independent copy.
Adjust Change only what differs.
1 / 2

The idea

The pattern needs only one operation, usually called clone(), declared by a common interface. Each class decides how to copy itself, which means the client never touches private fields or concrete constructors.

classDiagram
    class Prototype {
        <<interface>>
        +clone() Prototype
    }
    class Monster {
        +name
        +health
        +loot
        +clone() Monster
    }
    class Client
    Prototype <|.. Monster
    Client --> Prototype : asks to clone

The client holds a Prototype and calls clone(); it never needs the concrete class.

Java ships with Cloneable and Object.clone(), but both are widely considered flawed (the interface has no clone method, and clone() does a shallow copy by default). Modern Java code prefers copy constructors or copy factory methods, and so does most C++ code.

Shallow versus deep copy

A shallow copy duplicates the object's own fields. If a field holds a reference to another object (an array, a map, a nested object), the copy and the original now share that same nested object. A change through one is visible through the other.

A deep copy also duplicates everything the object refers to, recursively, so the two objects are fully independent.

JS The shared-reference trap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first block shows the bug that bites everyone once: pushing "map" into the shallow copy also changed the original, because both objects point at the same array. The structuredClone call fixes it by copying the array too.

What structuredClone can and cannot copy

structuredClone(value) is built into modern browsers and Node.js. It handles plain objects, arrays, Map, Set, Date, typed arrays and even circular references. It cannot copy functions or class methods (it throws), and it drops prototypes: a cloned class instance becomes a plain object. So for objects with behavior, write your own clone() that rebuilds the right class. JSON.parse(JSON.stringify(x)) is an older trick that also loses dates, Maps and undefined, so avoid it for anything but plain data.

A prototype registry

Often you keep a small set of ready-made prototypes and stamp out copies on request. This is a prototype registry (or prototype manager): a lookup table from names to prototypes. It combines naturally with Factory Method: the factory's job becomes "find the prototype and clone it".

JS Monster prototypes in a registry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Because clone() copies loot, the goblin chief's crown does not appear in later goblins. The registry never needs to know Monster's fields, only that its entries answer clone().

Real systems use this idea constantly: a game spawning thousands of enemies from templates, a design tool duplicating a styled shape, a spreadsheet copying a row, or a test suite building users from a base fixture and changing one field.

Copy constructors in C++

C++ already has a built-in notion of copying: the copy constructor. Its default version copies each member (a shallow copy of pointers), which is exactly the sharing trap again. Classes that own heap memory must define their own. This read-only example shows both the copy constructor and a polymorphic clone() virtual function, the usual way to clone through a base pointer:

C++
#include <memory>
#include <string>
#include <vector>

class Shape {
public:
    virtual ~Shape() = default;
    // Copy through a base pointer: each subclass returns its own type.
    virtual std::unique_ptr<Shape> clone() const = 0;
};

class Polygon : public Shape {
    std::string label_;
    std::vector<int> points_;          // owns its data, so a copy is deep
public:
    Polygon(std::string label, std::vector<int> points)
        : label_(std::move(label)), points_(std::move(points)) {}

    Polygon(const Polygon&) = default; // member-wise copy is already deep here

    std::unique_ptr<Shape> clone() const override {
        return std::make_unique<Polygon>(*this);
    }
};

Value members such as std::string and std::vector copy deeply by themselves, so the default copy constructor is correct. The default becomes a bug only when the class holds a raw pointer or another shared resource. Modern C++ advice: store values or smart pointers, and the compiler-generated copy usually does the right thing. For Python, the standard copy module offers copy.copy (shallow) and copy.deepcopy, and classes can customize with __copy__ and __deepcopy__.

Pitfalls

  • Hidden shallow copies: the number one bug. When in doubt, test by changing a nested value in the clone and checking the original.
  • Circular references: a naive recursive deep copy loops forever on cycles. structuredClone and copy.deepcopy handle them; hand-written clones must too.
  • Identity fields: copies of an entity often need a new id. Reset ids, timestamps and unique keys after cloning.
  • Resources: you cannot meaningfully clone an open file, socket or database connection. Clone the description, then reopen.
  • Cost: a deep copy of a huge object graph can be slower than constructing a new one. Measure before assuming cloning is faster.

Prototype is rarely the first creational pattern to reach for, but it is perfect when objects are mostly alike. Together with Singleton, Abstract Factory and Builder, it completes the classic creational set; the final lesson of this chapter covers pooling and lazy creation.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Prototype pattern do?

    Prototype creates objects by cloning a configured instance rather than constructing from scratch.
  2. 2. A shallow copy of an object that contains an array field has what property?

    A shallow copy copies references, so the nested array is shared. Changing it through one object changes it in the other.
  3. 3. Which statement about structuredClone is correct?

    structuredClone performs a deep copy of structured data; functions throw an error and class instances become plain objects.
  4. 4. What is the purpose of a prototype registry?

    A registry maps names to prototypes, so clients obtain a fresh copy by key without knowing how it was configured.
  5. 5. In C++, when does the compiler-generated copy constructor become a bug?

    The default copies the pointer, not the data it points to, so two objects would share and later double-free the same memory.

Summary

  • Prototype creates new objects by cloning a configured instance through a clone() operation.
  • A shallow copy shares nested objects; a deep copy duplicates them. Test nested changes to be sure.
  • structuredClone deep-copies plain data in JavaScript but loses methods and prototypes; Python has copy.copy and copy.deepcopy.
  • A registry of named prototypes lets clients spawn objects without knowing their setup.
  • In C++, the copy constructor and a virtual clone() implement the pattern; own your memory with values or smart pointers.
  • Reset identity fields after cloning and watch for cycles and unclonable resources.

Next lesson: Object Pool, Lazy Initialization and Dependency-Free Creation.