Cheatsheet

Factory Method

Intent

Define a method for creating an object, but let subclasses decide which concrete class to instantiate.

Structure (UML)

Spring contextAmrapPlannerAmrapWodServiceWodControllerEmomPlannerEmom«i»WodPlannerForTimePlannerForTimeCoach

Participants

  • Product (Workout), the interface of what gets created
  • ConcreteProduct (Amrap, Emom, ForTime), each WOD format
  • Creator (WodPlanner), with the template method plan() that uses the factory method createWorkout()
  • ConcreteCreator (AmrapPlanner, EmomPlanner, ForTimePlanner), which decide which product to build

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);

Pros

  • The code that uses the product doesn't know the concrete classes
  • A new format is a new product and a new creator; nothing else changes
  • The knowledge of how to build each type lives with whoever owns it

Cons

  • A creator hierarchy parallel to the product one, which can feel like a lot for simple cases
  • If creating is trivial, a constructor or a static method is enough
  • It relies on inheritance, so the concrete creator is tied to the base class

← Factory Method · Run it