Design Patterns
Prototype
Cloning one object takes O(n) time, where n is the number of fields you copy. That's much cheaper than rebuilding everything field by field.
The idea, in plain English
The prototype pattern makes new objects by copying an existing one, instead of building it from scratch. It's like photocopying a filled-out form and just changing the name field, instead of drawing a brand new blank form and filling in every line again.
How it works
- 1You start with one fully set-up object to use as the 'prototype'.
- 2You call a clone method on it. That method copies its fields into a brand new object.
- 3You tweak only the parts of the copy that need to be different. Everything else comes for free.
When you'd use it
Use this when making a new object from scratch is slow or repetitive, and most new objects look almost identical to one you already have. Examples: game characters, document templates, or preset settings.
Common beginner mistakes
- Don't do a 'shallow' copy when you need a 'deep' copy. A shallow copy leaves both objects secretly sharing the same nested data.
- Keep the original prototype unchanged. Editing a clone should never affect the prototype it came from.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Aragorn: 100 HP, Sword
Legolas: 100 HP, Bow
Prototype unchanged: WarriorNot sure this is the right topic? See the learning paths → or where this leads →