Card 08/ 08

RecapDifficulty: Advanced1 min

Recap: Prototype Pattern

Copy a configured object instead of rebuilding it, and know how deep the copy goes.

Prototype creates new objects by copying a configured one, so the set-up is done once and a client need not know the class.

  • Intent. Specify the kinds of objects to create using a prototypical instance, and create new objects by copying it.
  • Participants. The prototype declares clone(); each concrete prototype copies itself; the client calls clone(), often through a registry of prototypes by name.
  • Recognise it by shape. New objects come from clone() or a copy of a configured object, not from a constructor followed by set-up.
  • In each language. copy.deepcopy in Python; clone() with Cloneable, or a copy constructor, in Java; structuredClone in TypeScript, which returns a plain object.
  • Not quite the pattern. Object.create links a new object to its prototype, so later changes to the prototype show through; a clone is independent.
  • The trap. A shallow copy shares nested lists and dictionaries with the original. Decide field by field what a clone must copy.