Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Prototype

Intent

Copy a ready-made example instead of rebuilding the same setup from scratch.

Motivation

A game spawns dozens of goblins sharing base stats with small tweaks (one is faster, one hits harder). Constructing each through the full setup repeats asset loads and risks drift. A prototype keeps one tuned goblin and clones it, then adjusts only what differs.

Structure

flowchart LR
  Client --> Proto[Prototype Registry]
  Proto --> Goblin[Base Goblin]
  Goblin --> CloneA[Clone A: faster]
  Goblin --> CloneB[Clone B: stronger]
  • Prototype — cloning contract returning an independent copy.
  • Concrete prototype — base goblin knowing how to duplicate itself.
  • Clones — copies tweaked after cloning without touching the original.

Adaptation note: in Elixir prefer copying immutable maps/structs; in Rust derive Clone; the lesson is clone-then-tweak, not a clone keyword.

Consequences

  • Benefit: fast varied copies without rerunning heavy setup; new variants need no new classes.
  • Cost: deep vs shallow copy mistakes; hidden sharing when nested state stays linked.

Basic Recap

Prototype creates a new object by copying a configured exemplar instead of rebuilding its state from scratch. The exemplar captures a useful starting point, and each clone receives the variations needed for its own use. The hard design decision is copy depth: immutable values can be shared, but mutable collaborators often need independent copies. A clone operation should make that ownership boundary explicit.

Complex Scenario

A document editor offers complex page templates containing nested text blocks, style objects, comment threads, and references to large image assets. Creating a page from a template should duplicate the editable block tree and comments while sharing immutable asset blobs. A prototype registry stores approved templates, and each clone receives fresh identifiers so later edits do not alter the exemplar. Simple field copying is unsafe because two pages would otherwise share mutable descendants.

Edge cases

  • Memory pressure: Deep-copying every image blob multiplies memory use; content-addressed immutable assets should be shared, with reference lifetimes managed independently from the editable page tree.
  • Concurrency: Two users cloning one template must not observe a temporary identifier remap or mutate shared clone bookkeeping.
  • Partial failure: Failure while copying one nested object must discard the incomplete clone and any newly allocated native resources, leaving the source template untouched.

Use a copy context to preserve cycles and repeated references deliberately, rather than letting each object recursively clone without coordination.

Sketch (illustrative pseudocode, not runnable):

TemplateRegistry.instantiate(templateId, owner):
    source = registry.approved(templateId)
    context = CopyContext(idAllocator, memo = {})
    draft = source.cloneUsing(context)
    draft.owner = owner
    draft.status = DRAFT
    return draft

Page.cloneUsing(context):
    copy = newPageSkeleton(freshId())
    context.memo[this] = copy
    copy.blocks = deepCopyMutable(blocks, context)
    copy.assets = shareImmutableReferences(assets)
    copy.comments = deepCopyMutable(comments, context)
    return copy

When to Use / When Not to Use

Use when:

  • Many similar objects differ slightly and setup is costly or repetitive.

Avoid when:

  • Copies must stay linked to the original or construction is already trivial.

Examples

  • examples/elixir/prototype/
  • examples/dart/prototype/
  • examples/go/prototype/
  • examples/rust/prototype/

Expected outcome: cloning a base goblin twice prints base plus two tweaked copies with independent stats.

Anti-pattern / Failure Mode

  • Misuse: Cloning shared mutable state so copies interfere with each other.

  • Review signal: Clones that need deep-copy fixes on every use — the prototype is not self-contained.

  • Misuse symptom: A generic clone method silently mixes shallow and deep copies, and prototypes are used mainly to avoid understandable constructors. Mutable caches, database sessions, or listeners accidentally survive cloning and connect the new object to the source’s lifetime.

  • Review signal: Check whether clone tests edit nested values in both objects and verify identity remapping. Fields copied by reflection without an explicit ownership policy, increasing resident memory after repeated clones, and source objects receiving clone events are all warning signs.

  • Builder — build fresh vs clone then tweak.
  • Flyweight — share repeatable state vs copy a tuned example.
  • Memento — snapshot for restore vs clone for reuse.

Exercise

Add a third clone with different health and prove editing it leaves the base unchanged.

Self-check

  • Shallow vs deep copy risk?
    AnswerNested mutable parts may stay shared after a shallow copy; deep copy duplicates them.
  • Prototype vs Factory?
    AnswerPrototype copies an existing instance; Factory builds a new one from parameters.