Cheatsheet
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.
Structure (UML)
classDiagram
direction LR
class FranPlanner {
<<Client>>
+plan(DivisionKit kit) WodCard
}
class DivisionKit {
<<AbstractFactory>>
+barbell() Barbell
+pull() PullVariant
+scorecard() Scorecard
}
class RxKit {
<<ConcreteFactory>>
}
class ScaledKit {
<<ConcreteFactory>>
}
class TeensKit {
<<ConcreteFactory>>
}
class Scorecard {
<<AbstractProduct>>
+score(seconds, reps, totalReps) String
}
class TimedScorecard {
<<ConcreteProduct>>
}
class TeensScorecard {
<<ConcreteProduct>>
}
FranPlanner --> DivisionKit
FranPlanner --> Scorecard
DivisionKit <|.. RxKit
DivisionKit <|.. ScaledKit
DivisionKit <|.. TeensKit
Scorecard <|.. TimedScorecard
Scorecard <|.. TeensScorecard
RxKit ..> TimedScorecard : creates
ScaledKit ..> TimedScorecard : creates
TeensKit ..> TeensScorecard : createsParticipants
- AbstractFactory (DivisionKit), the interface with one method per piece of the family
- ConcreteFactory (RxKit, ScaledKit, TeensKit), one per family
- AbstractProduct (Scorecard), a piece with one implementation per family that scores differently; Barbell and PullVariant are data pieces
- Client (FranPlanner), which puts the WOD together with whatever factory it's given
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();
}Pros
- Pieces from one family never get mixed with another's
- The client knows no concrete division
- A new family is one more class, without touching the client
Cons
- A new piece in the family means touching the interface and every factory
- If only one piece varies, it's more structure than needed
- There are more types to follow to understand where each thing comes from