Factory Method
- Intent
- Define a method for creating an object, but let subclasses decide which concrete class to instantiate.
- Application
- AMRAP, EMOM and For Time are described and scored differently. Let each planner decide which kind of WOD to build, and keep the rest of the code unaware of which class comes out.
The coach sends AMRAP 20' to WodController, which calls SwitchingWodService, highlighted in red: a single service that builds each format's text by hand.
The diagram doesn't change: SwitchingWodService stays highlighted in red, with one switch for everything that depends on the format.
The abstract WodPlanner appears, highlighted, with three planners implementing it.
The three planners, highlighted, each build their product: new Amrap(), new Emom() and new ForTime().
The Spring context appears. WodService, highlighted together with the context, is wired to the three planners, which implement WodPlanner and build their products.
Cindy · AMRAP 20' travels from the coach to the controller, plan() to WodService and on to AmrapPlanner, highlighted, which builds an Amrap, also highlighted.
WodService sends plan() to ForTimePlanner, highlighted, which builds a ForTime, also highlighted.
Inside the Spring context, DailyWodFactoryBean, highlighted, sends getObject() and hands over an Amrap.
Final view: the coach, the controller, WodService, the three planners implementing WodPlanner and their products, all inside the Spring context.
Step 1 of 9
A service that knows every format
The coach programs the week's WODs in the app. There are three formats, each described and scored differently:
- AMRAP: as many rounds as possible in a set time; scored in rounds and reps.
- EMOM: every minute you start again; scored in completed minutes.
- For Time: finish the work as fast as you can, within a time cap; scored in seconds, and lower is better (if you hit the cap, your completed reps count instead).
SwitchingWodService handles it with a switch on the format to build the description.
Step 2 of 9
The same switch, twice
Look further down: there's another switch on the format for the scoring unit, and a stray format.equals("for-time") check to know whether lower is better.
Adding Tabata means touching both switches and that check, and remembering all of them. Each format is scattered across the service instead of living in one place.
Step 3 of 9
The creator doesn't know what it creates
Factory Method separates using an object from deciding which class it is:
Workoutis the product: it describes the WOD and says how it's scored.WodPlanneris the creator. Itsplan()method builds the whiteboard plan, but to get theWorkoutit callscreateWorkout(), an abstract method.
plan() works the same for any format. The question "which kind of Workout?" is left to the subclasses.
Step 4 of 9
One creator per format
Each format has its creator:
AmrapPlannerreturns anew Amrap(...).EmomPlannerreturns anew Emom(...).ForTimePlannerreturns anew ForTime(...).
And each product knows how to describe and score itself. There's no switch left: the decision is spread over small classes, each knowing its own part.
Step 5 of 9
Creators are beans
Each planner is a @Component. WodService gets every WodPlanner in the context and keeps them in a map by format (amrap, emom, for-time).
When a request comes in, it looks up that format's planner and asks it for the plan. If the format doesn't exist, it answers 400.
Step 6 of 9
Cindy, a 20-minute AMRAP
The coach programs Cindy: POST /api/wods/plan with format amrap, 20 minutes and three movements.
WodServicelooks up theamrapplanner.AmrapPlanner.plan()calls itscreateWorkout(), which builds anAmrap.- The whiteboard gets "AMRAP 20': 5 pull-ups, 10 push-ups, 15 air squats", scored in rounds and reps.
The example test makes that same request by calling WodService directly.
Step 7 of 9
Each creator knows its own part
In For Time, the request's minutes aren't the duration but the time cap: Fran with an 8-minute cap. Only ForTimePlanner knows to read it that way, and it creates a ForTime where less time is better.
That knowledge lives in the format's creator, not in ifs scattered across the service.
Step 8 of 9
Spring already does it for you
In a broad sense, Spring is full of "methods that create": BeanFactory.getBean(...) hands you objects without a new, and Spring's documentation calls every @Bean method a factory method. But they aren't the GoF pattern, because there's no subclass deciding which class to create.
The closest match to the pattern is FactoryBean: a bean whose job is to make another object. Spring registers the FactoryBean and, when someone asks for that bean, calls its getObject(); since isSingleton() is true by default, the result is cached and reused. In the example, DailyWodFactoryBean decides the WOD of the day: ask for "dailyWod" and you get an Amrap; ask for "&dailyWod" and you get the factory.
Step 9 of 9
Recap
You started with a service that had a switch per format and ended up with:
- One product,
Workout, with one class per format. - One creator,
WodPlanner, whoseplan()uses an abstract factory method. - One concrete creator per format, as a bean, deciding what to build.
FactoryBean, when you want the container itself to call your factory.
Code
SwitchingWodService.java
public WodPlan plan(WodRequest r) {
String movements = String.join(", ", r.movements());
String summary = switch (r.format()) { // switch #1: how to describe it
case "amrap" -> "AMRAP " + r.minutes() + "': " + movements;
case "emom" -> "EMOM " + r.minutes() + "': " + movements;
case "for-time" -> "For time (cap " + r.minutes() + "'): " + movements;
default -> throw new IllegalArgumentException("unknown format: " + r.format());
};
String scoreUnit = switch (r.format()) { // switch #2: how to score it
case "amrap" -> "rounds + reps";
case "emom" -> "completed minutes";
case "for-time" -> "seconds";
default -> throw new IllegalArgumentException("unknown format: " + r.format());
};
return new WodPlan(r.name(), r.format(), summary, scoreUnit, r.format().equals("for-time"));
}SwitchingWodService.java
public WodPlan plan(WodRequest r) {
String movements = String.join(", ", r.movements());
String summary = switch (r.format()) { // switch #1: how to describe it
case "amrap" -> "AMRAP " + r.minutes() + "': " + movements;
case "emom" -> "EMOM " + r.minutes() + "': " + movements;
case "for-time" -> "For time (cap " + r.minutes() + "'): " + movements;
default -> throw new IllegalArgumentException("unknown format: " + r.format());
};
String scoreUnit = switch (r.format()) { // switch #2: how to score it
case "amrap" -> "rounds + reps";
case "emom" -> "completed minutes";
case "for-time" -> "seconds";
default -> throw new IllegalArgumentException("unknown format: " + r.format());
};
return new WodPlan(r.name(), r.format(), summary, scoreUnit, r.format().equals("for-time"));
}WodPlanner.java
public final WodPlan plan(WodRequest request) {
Workout workout = createWorkout(request); // the factory method: the subclass picks the class
return new WodPlan(request.name(), format(), workout.summary(), workout.scoreUnit(), workout.lowerIsBetter());
}
protected abstract Workout createWorkout(WodRequest request);AmrapPlanner.java
@Component
public class AmrapPlanner extends WodPlanner {
@Override
public String format() {
return "amrap";
}
@Override
protected Workout createWorkout(WodRequest request) {
return new Amrap(request.minutes(), request.movements());
}
}WodService.java
public WodService(List<WodPlanner> planners) {
// every WodPlanner bean, indexed by the format it handles
for (WodPlanner p : planners) {
if (this.planners.putIfAbsent(p.format().toLowerCase(Locale.ROOT), p) != null) {
throw new IllegalStateException("two planners for format: " + p.format());
}
}
}
public WodPlan plan(WodRequest request) {
String asked = request.format().strip();
WodPlanner planner = planners.get(asked.toLowerCase(Locale.ROOT));
if (planner == null) {
throw new IllegalArgumentException("unknown format: " + abbreviate(asked));
}
return planner.plan(request); // which Workout class gets built is the planner's call
}WodServiceTest.java
WodPlan plan = wods.plan(new WodRequest("Cindy", "amrap", 20, List.of("5 pull-ups", "10 push-ups", "15 air squats")));
assertThat(plan.summary()).isEqualTo("AMRAP 20': 5 pull-ups, 10 push-ups, 15 air squats");
assertThat(plan.scoreUnit()).isEqualTo("rounds + reps");
assertThat(plan.lowerIsBetter()).isFalse();ForTimePlanner.java
@Override
protected Workout createWorkout(WodRequest request) {
// here "minutes" means the time cap: only this creator knows that
return new ForTime(request.minutes(), request.movements());
}SpringDoesItTooTest.java
/** A bean whose job is to make another object: Spring calls getObject() and registers the result. */
static class DailyWodFactoryBean implements FactoryBean<Workout> {
@Override
public Workout getObject() {
return new Amrap(12, List.of("10 wall balls", "10 box jumps")); // today's WOD, decided here
}
@Override
public Class<?> getObjectType() {
return Workout.class;
}
}WodPlanner.java
public final WodPlan plan(WodRequest request) {
Workout workout = createWorkout(request); // the factory method: the subclass picks the class
return new WodPlan(request.name(), format(), workout.summary(), workout.scoreUnit(), workout.lowerIsBetter());
}
protected abstract Workout createWorkout(WodRequest request);