Cheatsheet

Prototype

Intent

Create new objects by copying an existing one that serves as a model, and let the object itself know how to be copied.

Structure (UML)

Spring contextCoachProgramLibrary30Strength blockWed: back squatWeekControllerWeekService30Week 47Wed (week 47)

Participants

  • Prototype (WeekProgram, DayPlan), which know how to copy themselves with copy(). In GoF the client copies through a shared interface without knowing the class; here every template is the same class and only its data differs
  • Prototype registry (ProgramLibrary), which keeps named templates and only hands out copies
  • Client (WeekService), which asks for a copy and customises it

WeekProgram.java

/** The prototype's copy: a new week with a copy of every day, not the same days. */
public WeekProgram copy() {
    List<DayPlan> copied = new ArrayList<>();
    for (DayPlan d : days) copied.add(d.copy());   // deep: each day copies itself
    return new WeekProgram(name, copied);
}

Pros

  • Creating a week like another is copying and changing what differs
  • Each class knows how to copy itself; nobody outside needs to know its fields
  • Templates don't get spoiled, because only copies go out

Cons

  • Deep copying needs every mutable piece to know how to copy itself, and it's easy to miss one
  • With cross-references or cycles, copying properly gets complicated
  • If an object holds identity or resources (an id, a connection), the copy needs adjusting after copying

← Prototype · Run it