Abstract Factory
- Intent
- Offer a way to create several pieces that belong together without saying which class each one is, so whoever uses them always gets a consistent family.
- Application
- Fran isn't the same for Rx, Scaled or Teens. The load, the pull-up variant and the board tag must always match. Ask a single factory per division for all three pieces and they'll never get mixed up.
The coach asks for Fran for rx; WodService calls IfElseFranPlanner, highlighted in red, with plan("rx").
The diagram doesn't change: IfElseFranPlanner stays highlighted in red; with plan("RX") the card comes out with pieces from two divisions.
The DivisionKit interface appears, highlighted, with three factories implementing it: RxKit, ScaledKit and TeensKit.
RxKit, highlighted, makes its three pieces: Barbell 43 kg with barbell(), pull-ups with pull() and Rx · 10' with scorecard().
FranPlanner, highlighted, asks DivisionKit for barbell(), pull() and scorecard().
The scorecard, highlighted together with TeensKit, is used with scorecard().score(…): each family scores its own way.
The Spring context appears. WodService, highlighted together with the context, has every factory at hand; FranPlanner, DivisionKit and the three kits are inside.
GET /api/wods/fran?division=scaled travels from the coach to the controller, fran("scaled") to the service and plan(scaledKit) to FranPlanner, which asks DivisionKit for its pieces; FranPlanner and ScaledKit are highlighted.
DataSource, a bean in the Spring context, hands out an H2 Connection, highlighted, which makes its Statement, its PreparedStatement and its CallableStatement.
Final view: the coach, the controller, WodService, FranPlanner and DivisionKit with its three kits, all inside the Spring context.
Step 1 of 10
Fran for each division
At the box, each athlete does Fran in their division. The board gives each one their own:
- Rx: thrusters at 43 kg, pull-ups, 10-minute cap.
- Scaled: 29 kg, jumping pull-ups, 12 minutes.
- Teens: 20 kg, ring rows, 12 minutes.
The first version, IfElseFranPlanner, decides each piece on its own: one if for the load, another for the pull-up and another for the tag.
Step 2 of 10
A mixed card
The load's if compares ignoring case and the tag's doesn't. All it takes is someone sending "RX": the card comes out with Rx loads and a Scaled tag, and someone who did the full WOD shows up as scaled on the leaderboard. The IfElseFranPlannerTest test proves it.
And every new division (Masters, adaptive) is four more ifs, in four places.
This particular bug could be fixed by normalising the text once, or with a Division enum. What Abstract Factory adds goes further: each family can bring pieces with different behaviour, and a new family doesn't touch the planner.
Step 3 of 10
One factory per family
Abstract Factory brings the creation of all the pieces into a single object. DivisionKit has one method per piece:
barbell(), the bar's load;pull(), the pull-up variant;scorecard(), the tag and the time cap.
Whoever has a DivisionKit can ask it for the three pieces, and all three will be from the same division.
Step 4 of 10
Each factory, its family
RxKit makes the 43 kg bar, the pull-ups and the 10-minute "Rx" card. ScaledKit and TeensKit do the same with their values.
There isn't a single if: each class is a division and gathers all its pieces in one place.
Step 5 of 10
The planner doesn't know which division it is
FranPlanner is the client: it gets a DivisionKit and asks it for the three pieces. With them it writes the card.
It doesn't know whether it's writing Fran for Rx or for Teens, and it doesn't need to. Since the three pieces come from the same kit, the card is always consistent.
Step 6 of 10
Each family scores its own way
The pieces aren't just data. Scorecard is an interface, and each family brings its own way of scoring:
- Rx and Scaled use
TimedScorecard: if you finish, your score is your time ("3:05 Rx"); if you hit the cap, your reps ("CAP + 72 reps Rx"). - Teens uses
TeensScorecard: it always counts reps inside the cap, so nobody rushes the barbell.
FranPlanner calls kit.scorecard().score(...) without knowing which one it got.
Step 7 of 10
The factories are beans
In Spring, each kit is a named @Component: "rx", "scaled", "teens". WodService gets a Map<String, DivisionKit> with all of them, keyed by that name.
When a request comes in, it normalises the division (Rx if none is given), looks up its kit in the map and hands it to the planner. If it doesn't exist, it answers 400.
Step 8 of 10
Fran Scaled
GET /api/wods/fran?division=scaled:
WodServicelooks up the"scaled"kit.FranPlannerasks it for the three pieces.- The card says "Fran · Scaled", "thrusters 29 kg" and "jumping pull-ups", with a 12-minute cap.
Without division, Rx is used. With a division that doesn't exist, the answer is 400 "unknown division".
Step 9 of 10
Spring already does it for you
In JDBC, Connection works as an abstract factory. Spring Boot gives you a DataSource, and every Connection that comes out of it makes the pieces of its database: createStatement(), prepareStatement(...) and prepareCall(...) return statements from the H2 driver.
Your code only sees the java.sql interfaces. Change the driver and the URL, and the whole family changes at once: you'll never get a PostgreSQL Connection with H2 statements. The connection pool (HikariCP) puts them in a wrapper of its own, but isWrapperFor confirms there are H2 statements underneath.
Step 10 of 10
Recap
You started with three ifs that could disagree and ended up with:
- An abstract factory,
DivisionKit, with one method per piece. - One concrete factory per family, as a named bean.
- A client,
FranPlanner, that puts the card together without knowing the division. - Families that don't mix, because they're picked only once.
Don't mix it up with its neighbours: Factory Method creates one piece with a method a subclass overrides; Abstract Factory is an object that creates several that belong together. Builder puts one complex object together step by step, and Prototype creates pieces by copying a model.
And when you don't need it: if only one piece varies, a Strategy or a Factory Method is enough; and if the families only differ in data (a few numbers, a few names), an enum with those values is simpler.
Code
IfElseFranPlanner.java
public List<String> plan(String division) {
int kg;
if (division.equalsIgnoreCase("rx")) kg = 43;
else if (division.equalsIgnoreCase("teens")) kg = 20;
else kg = 29;
String pull;
if (division.equalsIgnoreCase("rx")) pull = "pull-ups";
else if (division.equalsIgnoreCase("teens")) pull = "ring rows";
else pull = "jumping pull-ups";
String tag;
if (division.equals("rx")) tag = "Rx"; // this one compares differently…
else if (division.equals("teens")) tag = "Teens";
else tag = "Scaled"; // …so "RX" gets Rx weights and a Scaled tag
int cap;
if (division.equalsIgnoreCase("rx")) cap = 10;
else cap = 12;
return List.of("Fran · " + tag, "thrusters " + kg + " kg", pull, "cap " + cap + "'");
}IfElseFranPlanner.java
public List<String> plan(String division) {
int kg;
if (division.equalsIgnoreCase("rx")) kg = 43;
else if (division.equalsIgnoreCase("teens")) kg = 20;
else kg = 29;
String pull;
if (division.equalsIgnoreCase("rx")) pull = "pull-ups";
else if (division.equalsIgnoreCase("teens")) pull = "ring rows";
else pull = "jumping pull-ups";
String tag;
if (division.equals("rx")) tag = "Rx"; // this one compares differently…
else if (division.equals("teens")) tag = "Teens";
else tag = "Scaled"; // …so "RX" gets Rx weights and a Scaled tag
int cap;
if (division.equalsIgnoreCase("rx")) cap = 10;
else cap = 12;
return List.of("Fran · " + tag, "thrusters " + kg + " kg", pull, "cap " + cap + "'");
}DivisionKit.java
/** The abstract factory: everything a WOD needs for one division, always from the same family. */
public interface DivisionKit {
Barbell barbell();
PullVariant pull();
Scorecard scorecard();
}RxKit.java
/** A concrete factory: the Rx family, as written in the WOD. */
@Component("rx")
public class RxKit implements DivisionKit {
@Override public Barbell barbell() { return new Barbell(43); }
@Override public PullVariant pull() { return new PullVariant("pull-ups"); }
@Override public Scorecard scorecard() { return new TimedScorecard("Rx", 10); }
}FranPlanner.java
public WodCard plan(DivisionKit kit) {
Barbell bar = kit.barbell(); // the three pieces come from one kit,
PullVariant pull = kit.pull(); // so they always belong together
Scorecard card = kit.scorecard();
return new WodCard("Fran · " + card.tag(),
List.of("21-15-9", bar.thrusters(), pull.name()),
card.timeCapMinutes());
}FranPlannerTest.java
assertThat(planner.score(new RxKit(), 185, 90)).isEqualTo("3:05 Rx"); // finished: time
assertThat(planner.score(new RxKit(), 600, 72)).isEqualTo("CAP + 72 reps Rx"); // capped: reps
assertThat(planner.score(new TeensKit(), 412, 90)).isEqualTo("90 reps Teens"); // teens: always repsWodService.java
public WodService(Map<String, DivisionKit> kits, FranPlanner planner) {
this.kits = Map.copyOf(kits); // one per DivisionKit bean, by name: rx, scaled, teens
this.planner = planner;
}
public WodCard fran(String division) {
return planner.plan(kit(division));
}
private DivisionKit kit(String division) {
String key = division == null || division.isBlank()
? "rx" : division.strip().toLowerCase(Locale.ROOT); // no division: Rx
DivisionKit kit = kits.get(key);
if (kit == null) throw new UnknownDivisionException(abbreviate(key));
return kit;
}WodApiTest.java
mvc.perform(get("/api/wods/fran").param("division", "scaled"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Fran · Scaled"))
.andExpect(jsonPath("$.lines[1]").value("thrusters 29 kg"))
.andExpect(jsonPath("$.lines[2]").value("jumping pull-ups"))
.andExpect(jsonPath("$.timeCapMinutes").value(12));SpringDoesItTooTest.java
try (Connection connection = dataSource.getConnection(); // the factory for this database…
Statement statement = connection.createStatement(); // …makes its statements
PreparedStatement prepared = connection.prepareStatement("select 1");
CallableStatement callable = connection.prepareCall("call 1")) {
assertThat(statement.isWrapperFor(org.h2.jdbc.JdbcStatement.class)).isTrue();
assertThat(prepared.isWrapperFor(org.h2.jdbc.JdbcPreparedStatement.class)).isTrue();
assertThat(callable.isWrapperFor(org.h2.jdbc.JdbcCallableStatement.class)).isTrue();
}DivisionKit.java
/** The abstract factory: everything a WOD needs for one division, always from the same family. */
public interface DivisionKit {
Barbell barbell();
PullVariant pull();
Scorecard scorecard();
}