Composite
- Intent
- Treat a single piece and a group of pieces the same way, so you can build trees as deep as needed and walk them without asking what each node is.
- Application
- A WOD can have rounds inside rounds. Make a single movement and a whole block answer the same questions, and the tree works itself out, however deep it goes.
WodController asks FlatWod, highlighted in red, for reps().
The diagram doesn't change: FlatWod stays highlighted in red; Helen doesn't fit its single level of rounds.
The WorkoutPart interface appears, highlighted, with three classes implementing it: Movement, Run and Block.
Movement and Run, highlighted, implement WorkoutPart.
Block, highlighted, implements WorkoutPart and also holds a list of WorkoutPart: its parts.
Murph's tree: Murph, highlighted, contains Run 1600 m, the 20 rounds block, also highlighted, and another Run 1600 m; the 20-round block contains 5 pull-ups, 10 push-ups and 15 air squats.
GET /api/wods/murph travels from the coach to the controller; reps() goes down from WodController to Murph and from Murph to its three children (the runs answer 0), and from the 20-round block to each movement. The whole tree is highlighted.
Inside the Spring context, CompositePropertySource, highlighted, asks downtown for the capacity (20) and box-defaults for the minutes (60).
Final view: the coach, the controller and Murph's tree, all inside the Spring context.
Step 1 of 9
The flat WOD
The box's board shows each WOD with its total reps and a time estimate. The first version, FlatWod, understands WODs as "N rounds of these movements":
reps()adds up one round's movements and multiplies by the rounds;seconds()does the same with time.
For Murph (run a mile, 20 rounds of 5 pull-ups, 10 push-ups and 15 air squats, and another mile) someone added two fields: runBeforeMeters and runAfterMeters.
Step 2 of 9
Helen doesn't fit
Helen is 3 rounds of: run 400 m, 21 kettlebell swings and 12 pull-ups. The run goes inside each round, and FlatWod has no way to say so: it can only run before or after everything.
You could add another field, runInsideEachRoundMeters. And then another one for an EMOM inside an AMRAP. Every new field is another case in reps(), in seconds() and in any other calculation you add.
Step 3 of 9
What everyone can do
Composite starts with the question you'd ask any piece of training, a single movement or a whole WOD. That's WorkoutPart:
reps(), the reps;seconds(), the estimated time;lines(), how it reads on the board.
It's the pattern's Component. The Jackson annotations are only there to receive the tree as JSON, with a type field on each node.
Step 4 of 9
The leaves
The leaves answer for themselves:
Movement(12 pull-ups): 12 reps, 3 seconds each in the estimate.Run(400 m): 0 reps, at 5 minutes per km.
They have no children and don't know they might be inside a block.
Step 5 of 9
The block
Block is the Composite: some rounds of other parts, which may be blocks themselves. To answer, it asks its children:
reps()is its rounds times the sum of each child's reps;lines()writes its header and, below it, each child's lines indented by two more spaces.
It doesn't ask whether a child is a movement, a run or another block. It's enough that it's a WorkoutPart.
Step 6 of 9
Murph as a tree
Murph no longer needs special fields:
- a "Murph" block of one round,
- with a run, a 20-round block and another run,
- and inside the 20-round block, the three movements.
Helen is another tree: a 3-round block with the run inside. The same code fits both, and any combination the coach comes up with.
Step 7 of 9
The question goes down the tree
GET /api/wods/murph:
WodControllerlooks Murph up in the library and asks it forreps(),seconds()andlines().- Murph asks its three children; the 20-round block asks its three movements.
- The answers come back up: 20 × (5 + 10 + 15) = 600 reps, about 46 minutes.
POST /api/wods/estimate accepts any tree as JSON. Since it comes from outside, Block refuses, as it's built, any tree that breaks the box's rules: 1 to 50 rounds, 1 to 10 parts, at most 4 levels and no more than 10,000 reps or 6 hours. By then Jackson has already read the whole body, so a real API also caps the request size (Jackson already caps nesting).
Step 8 of 9
Spring already does it for you
A CompositePropertySource is a PropertySource… made of PropertySources. When you ask it for a property, it asks its sources in order and returns the first one that has it. In the example, downtown answers the capacity (20) and the minutes fall through to box-defaults (60). And since it's just another PropertySource, it can go inside another one.
There's more in Spring: HandlerMethodArgumentResolverComposite is an argument resolver made of resolvers, CompositeCacheManager brings several cache managers together, and in Actuator, /actuator/health is a tree of health indicators.
Step 9 of 9
Recap
You started with a flat WOD full of special fields and ended up with:
- A Component,
WorkoutPart, with the questions you'd ask any part. - Leaves,
MovementandRun, that answer for themselves. - A Composite,
Block, that answers by asking its children. - Limits when building trees that come from outside.
Here the parts are given when the block is created and can't be added later. Other versions of the pattern put add() and remove() on the group, or even on the shared interface; it's a trade-off between convenience and safety.
Don't mix it up with its neighbours: Decorator wraps one object and adds behaviour; Composite groups many and adds up their answers. Iterator walks the tree from outside, and Visitor helps when you keep adding new operations (calories, equipment needed…) without wanting to touch every class.
And when you don't need it: if the structure always has the same shape and the same depth, a class with its fields is clearer.
Code
FlatWod.java
public int reps() {
int perRound = 0;
for (FlatMovement m : movements) perRound += m.reps();
return rounds * perRound;
}
public int seconds() {
int perRound = 0;
for (FlatMovement m : movements) perRound += m.reps() * 3;
int runs = (runBeforeMeters + runAfterMeters) * 300 / 1000; // bolted on for Murph
return rounds * perRound + runs; // a run inside each round? no way to say it
}FlatWod.java
public int reps() {
int perRound = 0;
for (FlatMovement m : movements) perRound += m.reps();
return rounds * perRound;
}
public int seconds() {
int perRound = 0;
for (FlatMovement m : movements) perRound += m.reps() * 3;
int runs = (runBeforeMeters + runAfterMeters) * 300 / 1000; // bolted on for Murph
return rounds * perRound + runs; // a run inside each round? no way to say it
}WorkoutPart.java
/** The component: anything that can go on the board, from one movement to a whole WOD. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Movement.class, name = "movement"),
@JsonSubTypes.Type(value = Run.class, name = "run"),
@JsonSubTypes.Type(value = Block.class, name = "block")})
public interface WorkoutPart {
int reps(); // total reps of the strength work
int seconds(); // estimated time
List<String> lines(); // how it reads on the board
default int depth() { // how many blocks deep (a leaf is 0)
return 0;
}
}Movement.java
@Override
public int seconds() {
return reps * SECONDS_PER_REP;
}
@Override
public List<String> lines() {
return List.of(reps + " " + name);
}Block.java
@Override
public int reps() {
return times * parts.stream().mapToInt(WorkoutPart::reps).sum(); // ask every child
}
@Override
public int seconds() {
return times * parts.stream().mapToInt(WorkoutPart::seconds).sum();
}
@Override
public List<String> lines() {
List<String> lines = new ArrayList<>();
lines.add(header());
for (WorkoutPart p : parts) {
p.lines().forEach(line -> lines.add(" " + line)); // one level deeper
}
return lines;
}WodLibrary.java
private static final WorkoutPart MURPH = new Block("Murph", 1, List.of(
new Run(1600),
new Block(null, 20, List.of( // a block inside a block
new Movement("pull-ups", 5),
new Movement("push-ups", 10),
new Movement("air squats", 15))),
new Run(1600)));WodApiTest.java
mvc.perform(get("/api/wods/murph"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.reps").value(600)) // 20 × (5 + 10 + 15)
.andExpect(jsonPath("$.minutes").value(46)) // 2 runs + 600 reps
.andExpect(jsonPath("$.board[2]").value(" 20 rounds"));SpringDoesItTooTest.java
var defaults = new MapPropertySource("box-defaults", Map.of("box.class.capacity", 12, "box.class.minutes", 60));
var downtown = new MapPropertySource("downtown", Map.of("box.class.capacity", 20));
var config = new CompositePropertySource("box");
config.addPropertySource(downtown); // asked first
config.addPropertySource(defaults);
Object capacity = config.getProperty("box.class.capacity"); // 20: downtown answers
Object minutes = config.getProperty("box.class.minutes"); // 60: falls through to the defaultsWorkoutPart.java
/** The component: anything that can go on the board, from one movement to a whole WOD. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Movement.class, name = "movement"),
@JsonSubTypes.Type(value = Run.class, name = "run"),
@JsonSubTypes.Type(value = Block.class, name = "block")})
public interface WorkoutPart {
int reps(); // total reps of the strength work
int seconds(); // estimated time
List<String> lines(); // how it reads on the board
default int depth() { // how many blocks deep (a leaf is 0)
return 0;
}
}