Deep Dive
low level designdesign patternsoop

Prototype: Clone a Ready-Made Object Instead of Rebuilding It

Constructing an object can be expensive and the client shouldn't need its class — so copy a preconfigured instance. The whole game is shallow vs deep copy, and getting it wrong aliases your original.

·17 min read
Medium

Your game spawns a wave of a thousand orcs. Each orc needs a rigged mesh, a stat block rolled from a template, an AI behavior tree, and a loadout — and assembling one from scratch means a disk read, a JSON parse, and a chunk of CPU. Do that a thousand times a wave and the frame budget is gone before anything moves on screen.

But here’s the thing: those thousand orcs are 99% identical. They share the same mesh, the same base stats, the same behavior tree. Constructing each one from its raw ingredients is like re-typing a document every time you need another copy — when there’s a photocopier three feet away. You already built one perfect orc. Why not just copy it?

That’s the entire idea. And it comes with one trap that has bitten every engineer at least once: you copy the orc, hand each copy its own loot, and suddenly picking up a sword on orc #457 gives the same sword to all thousand of them. The copy wasn’t as independent as you thought.

The intuition: photocopy, don’t re-type

Two ways to get a second copy of a filled-out form. You can grab a blank and re-type every field by hand — that’s calling a constructor and re-running all the setup. Or you can drop the filled form on a photocopier and press the button — that’s prototype.clone(). The copier doesn’t need to know what the form means, how many fields it has, or which office produced it. It just duplicates whatever you feed it. Copying a working instance is cheaper and less error-prone than reconstructing one from first principles — provided the copy is truly independent, and not quietly sharing pages with the original.

From here the members-only deep dive picks up: an interactive cloner that shows the shared-reference leak turn red in real time, the shallow-vs-deep bug and its fix in three languages, the prototype registry that clones by key without naming the class, the tradeoffs and edge cases (cycles, non-copyable resources, Java’s Cloneable gotchas), and an interview corner with a hands-on coding challenge.

Members only

Keep reading with Premium

You've reached the members-only part of this deep-dive — the full implementation, the interactive ring simulator, and the step-by-step walkthrough. Unlock it with a membership.

Related Articles