Cheatsheet
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.
Structure (UML)
classDiagram
direction LR
class WodSummary {
<<Client>>
+of(WorkoutPart wod)$ WodSummary
}
class WorkoutPart {
<<Component>>
+reps() int
+seconds() int
+lines() List~String~
}
class Movement {
<<Leaf>>
}
class Run {
<<Leaf>>
}
class Block {
<<Composite>>
+parts() List~WorkoutPart~
}
WodSummary --> WorkoutPart
WorkoutPart <|.. Movement
WorkoutPart <|.. Run
WorkoutPart <|.. Block
Block o-- WorkoutPart : partsParticipants
- Component (WorkoutPart), what every node can do, leaf or group
- Leaf (Movement, Run), a node with no children that answers for itself
- Composite (Block), a node with children that answers by asking them
- Client (WodController, WodSummary), which treats any node the same, a single movement or a whole WOD
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;
}
}Pros
- The client doesn't tell a piece from a group
- Trees can be any depth without special code for each level
- A new kind of leaf is one more class; blocks don't change
Cons
- A shared interface can end up too thin or too general if leaves and groups have little in common
- It's easy to forget limits (depth, size) when the tree comes from outside
- If the structure is always flat, it's more code than you need
- Every new operation (calories(), say) means touching every class in the tree