AlgoViz

Prototype

medium 50 min

The Prototype pattern makes new objects by copying an existing one.

Watch lesson4:34

Where it shows up

The same pattern appears across everyday software.

  • Python: the copy module

    `copy.copy` is shallow and `copy.deepcopy` is deep. The documentation names the two problems of deep copies, recursive objects and copying too much, and solves them with a memo dictionary and the hooks `__copy__` and `__deepcopy__`.

  • Browsers: structuredClone

    Deep copies JavaScript data, circular references included. It throws DataCloneError for what can not be copied, and it does not walk or copy the prototype chain, so class instances lose their methods.

  • Browsers: Node.cloneNode

    Copies an element, with the parameter `deep` for its subtree. Attributes are copied, listeners added with addEventListener are not: a real example of reset.

  • Unity: Object.Instantiate

    Clones an object and sets position and rotation of the clone. Spawning enemies from a prepared prefab is this call.

  • Linux: fork

    A new process is a copy of its parent. The manual page says that pages are copied on write, so the cost is the page tables and a task structure.

  • Go: http.Request.Clone

    Returns a deep copy of a request with another context. The documentation adds that the Body is only copied shallow: one stream can not have two readers.

  • Django: copying model instances

    There is no built-in method. The documentation sets the primary key to None and `_state.adding` to True, then saves: copy the fields, renew the identity.

  • React: cloneElement

    Creates an element using another one as a starting point, with changed props. The React documentation calls it uncommon and says that it can lead to fragile code.

  • C# and .NET: MemberwiseClone and ICloneable

    MemberwiseClone is a shallow copy. For ICloneable, Microsoft recommends not to implement it in public APIs, because callers can not depend on a predictable copy.

  • JavaScript: Object.create

    Makes a new object with an existing object as its prototype. It shares the name with the pattern, but missing properties are looked up at each read and nothing is copied.