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.
- Application
- The coach doesn't program each week from scratch, but copies a template and changes one day. Make each object know how to copy itself completely, so editing the copy never touches the original.
ShallowCopyService, highlighted in red, creates Week 47 with a new list but the same days; editing Wednesday from Week 47 edits Week 46's, also highlighted.
The diagram doesn't change: ShallowCopyService stays highlighted in red, copying from outside.
Week 46 and Week 47, highlighted: copy() creates the new week from the previous one.
Week 47's Wednesday, highlighted, has its own list of movements.
ProgramLibrary, highlighted, looks up "strength-block" and creates Week 47 with copy().rename("Week 47").
The template's Wednesday and Week 47's, highlighted, are now different objects: editing one doesn't change the other.
POST /api/weeks travels from the coach to the controller, create() to WeekService and newWeek() to ProgramLibrary, which copies the template into Week 47; WeekService and Week 47 are highlighted (the Wednesday edit and the template check aren't animated).
Inside the Spring context, a singleton BeanDefinition is cloned with cloneBeanDefinition() into a copy with prototype scope, highlighted.
Final view: the coach, the controller, WeekService, ProgramLibrary, the template and Week 47 with their Wednesdays, all inside the Spring context.
Step 1 of 9
Copying last week
Every week, the coach starts from the previous week (or a template) and changes some day. The first version, ShallowCopyService, copies Week 46 from outside: it creates Week 47 with a new list of days.
But the days in that list are the same objects. When the coach changes Week 47's Wednesday to front squats, the previous week's Wednesday changes too. The ShallowCopyServiceTest test proves it.
Step 2 of 9
Copying from outside
On top of that, whoever copies has to know what the week looks like inside: which fields it has and which ones must be copied deeply. If tomorrow DayPlan gains a mutable field (the coach's notes, say), every place that copies weeks has to be remembered and touched.
Step 3 of 9
Each object knows how to copy itself
Prototype puts the copy inside the object: WeekProgram.copy() creates a new week and, for each day, asks it for its copy.
Whoever needs a week like another just does week46.copy() and changes what's needed. They don't know what fields a week has or what must be copied deeply.
In GoF, the client also copies through a shared interface without knowing the prototype's class. Here every week is the same class and only its data differs, which is the most common form day to day.
Step 4 of 9
The copy goes all the way down
DayPlan.copy() creates a new day with its own list of movements (the constructor copies it). So the copy is deep at every level: a new week, new days, new lists.
Java has Object.clone(), but it's shallow by default, forces you to implement Cloneable and has odd rules. A copy() method (or a copy constructor) is clearer.
Step 5 of 9
Named templates
ProgramLibrary keeps the prototypes by name: "strength-block" and "deload-week". To create a week, it copies the template and renames it: prototype(template).copy().rename(name).
Templates never leave the library: even to show one, it hands out a copy. That way nobody can spoil them by accident.
Step 6 of 9
Edit the copy, without fear
The test does what used to fail: it creates Week 47 from "strength-block", changes its Wednesday and checks that the template still has back squats and Helen. Other tests check that changing a copy of the template doesn't touch the original either.
Step 7 of 9
Through the API
POST /api/weekswithtemplate: "strength-block"andname: "Week 47": 201 and the new week. (To copy a stored week,POST /api/weeks/{id}/copydoes the same with itscopy().)PUT /api/weeks/{id}/days/Wedwith the new movements.GET /api/templates/strength-block: the template is unchanged.
Templates or weeks that don't exist give 404; an empty name or a day with no movements, 400.
Step 8 of 9
Spring already does it for you
Careful with the name: Spring's prototype scope doesn't copy any object. Every time you ask for the bean, it creates a new one from its definition, with its constructor and dependencies.
Where Spring does use the Prototype idea is in the bean definitions themselves: cloneBeanDefinition() returns a copy of a definition that you can change (its scope, say) without touching the original. And this one is the GoF form: the method is abstract on AbstractBeanDefinition and each kind of definition knows how to copy itself. And when combining a child definition with its parent's, Spring starts from a copy of the parent's and applies the child's changes.
Step 9 of 9
Recap
You started with a shallow copy that shared the days and ended up with:
- Objects that know how to copy themselves,
WeekProgramandDayPlan, deeply. - A prototype registry,
ProgramLibrary, that only hands out copies. - A client that copies and customises without knowing a week's insides.
Don't mix it up with its neighbours: Abstract Factory creates families of objects with one concrete factory per family; Prototype creates objects by copying a model, and sometimes a factory keeps prototypes and copies them. Memento also copies state, but to be able to go back, not to create new objects. And copying a Composite means copying its whole tree: exactly this lesson's deep copy.
And when you don't need it: if the objects are immutable, sharing them is safe and there's nothing to copy; and if building one from scratch is just as easy, a constructor or a builder is enough.
Code
ShallowCopyService.java
public WeekProgram duplicate(WeekProgram lastWeek, String newName) {
return new WeekProgram(newName, lastWeek.days()); // a new list… of the same days
}ShallowCopyService.java
public WeekProgram duplicate(WeekProgram lastWeek, String newName) {
return new WeekProgram(newName, lastWeek.days()); // a new list… of the same days
}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);
}DayPlan.java
/** A copy with its own list of movements, so editing one never touches the other. */
public DayPlan copy() {
return new DayPlan(day, movements); // the constructor copies the list
}ProgramLibrary.java
public WeekProgram newWeek(String template, String name) {
return prototype(template).copy().rename(name); // copy the template, then customise the copy
}WeekProgramTest.java
WeekProgram template = library.template("strength-block");
WeekProgram week47 = library.newWeek("strength-block", "Week 47");
week47.day("Wed").replace(List.of("5x3 front squat", "EMOM 10' cleans"));
assertThat(template.day("Wed").movements()).containsExactly("5x5 back squat", "3 rounds Helen");WeekApiTest.java
String location = mvc.perform(post("/api/weeks").contentType(MediaType.APPLICATION_JSON)
.content("{\"template\":\"strength-block\",\"name\":\"Week 47\"}"))
.andExpect(status().isCreated())
.andReturn().getResponse().getHeader("Location");
mvc.perform(put(location + "/days/Wed").contentType(MediaType.APPLICATION_JSON)
.content("{\"movements\":[\"5x3 front squat\",\"EMOM 10' cleans\"]}"))
.andExpect(jsonPath("$.days[2].movements[0]").value("5x3 front squat"));
mvc.perform(get("/api/templates/strength-block"))
.andExpect(jsonPath("$.days[2].movements[0]").value("5x5 back squat")); // the template is untouchedSpringDoesItTooTest.java
GenericBeanDefinition base = new GenericBeanDefinition();
base.setBeanClass(ArrayList.class);
base.setScope(BeanDefinition.SCOPE_SINGLETON);
AbstractBeanDefinition copy = base.cloneBeanDefinition(); // a copy of the definition…
copy.setScope(BeanDefinition.SCOPE_PROTOTYPE); // …changed without touching the original
assertThat(base.getScope()).isEqualTo(BeanDefinition.SCOPE_SINGLETON);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);
}