Prototype Pattern
The Prototype pattern: creating new objects by copying a configured one, and the shallow copy trap that comes with it.
Some objects take real work to set up: stats loaded from a file, a dozen fields chosen with care, or a class the calling code does not even know. The Prototype pattern skips that work for every object after the first, by configuring one object and copying it whenever another like it is needed.
This topic opens on that problem and the pattern's intent, then reads its participants off a short class diagram and the registry of named prototypes that usually goes with it. The template shows the copy each language makes: copy.deepcopy in Python, clone() in Java and structuredClone in TypeScript.
Two examples follow: enemies in a game, each spawned from a configured template, and JavaScript's Object.create, which makes a new object from an existing one by linking to it rather than copying it. The gotcha is the copy that goes only one level deep, so that clones share a list, and the exercise decides, field by field, how deep a document template's copy must go.
By the end you can recognise a prototype, and predict what a copy shares with the object it was copied from.
Contents
8 cardsnot started