Card 08/ 08
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 callsclone(), 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.deepcopyin Python;clone()withCloneable, or a copy constructor, in Java;structuredClonein TypeScript, which returns a plain object. - Not quite the pattern.
Object.createlinks 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.
← → move through sections and cards