Cheatsheet
Factory Method
Intent
Define a method for creating an object, but let subclasses decide which concrete class to instantiate.
Structure (UML)
classDiagram
direction LR
class WodPlanner {
<<Creator>>
+plan(WodRequest request) WodPlan
#createWorkout(WodRequest request) Workout
}
class AmrapPlanner {
<<ConcreteCreator>>
#createWorkout(WodRequest request) Workout
}
class EmomPlanner {
<<ConcreteCreator>>
}
class ForTimePlanner {
<<ConcreteCreator>>
}
class Workout {
<<Product>>
+summary() String
+scoreUnit() String
}
class Amrap {
<<ConcreteProduct>>
}
class Emom {
<<ConcreteProduct>>
}
class ForTime {
<<ConcreteProduct>>
}
WodPlanner <|-- AmrapPlanner
WodPlanner <|-- EmomPlanner
WodPlanner <|-- ForTimePlanner
WodPlanner ..> Workout : uses
Workout <|.. Amrap
Workout <|.. Emom
Workout <|.. ForTime
AmrapPlanner ..> Amrap : creates
EmomPlanner ..> Emom : creates
ForTimePlanner ..> ForTime : createsParticipants
- 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