Skip to main content
Design Patterns 80 XP · 8 min

Prototype: Object Cloning

Copy existing objects without depending on their classes — clone complex configurations instead of rebuilding them from scratch.

Showing
Ad (728×90)

Why this matters

Some objects are expensive to construct — they require database lookups, heavy computation, or dozens of configuration fields. When you need a second object that is mostly the same, rebuilding it from scratch is wasteful and error-prone. The Prototype pattern gives every object a clone() method — you copy the expensive object and override only what differs, without knowing the object's concrete class.

The problem

Bad

The solution

Good

Deep copy vs shallow copy

The critical detail in Prototype is ensuring your clone is truly independent. A shallow copy shares nested object references — mutating the clone mutates the original. Always deep-copy any mutable nested structures. In Python, dataclasses.replace() is shallow but safe for flat dataclasses. In TypeScript, spread operators are shallow — for nested objects, copy each level explicitly or use structuredClone().

Key takeaway

If creating an object is costly and you need variations of an existing one, clone it — Prototype avoids re-running the expensive setup.

Done with this lesson?

Mark it complete to earn XP and track your progress.