13 — Behavioral Patterns I¶
Driving question: How should responsibility move when behavior varies independently from data?
Learning objectives¶
- Use Strategy, Template Method, State, and Command appropriately.
- Compare composition-based and inheritance-based variation.
- Model state transitions explicitly.
- Recognize conditional complexity that can—but need not—motivate a pattern.
Variation axes¶
Strategy isolates a family of interchangeable algorithms. Template Method fixes an algorithm skeleton and allows selected steps to vary. State moves state-dependent behavior into state objects. Command reifies an action as an object to enable queuing, undo, logging, retry, or composition.
Conditional logic is not automatically a smell¶
A small switch over a closed stable enum may be clearer than a hierarchy of tiny classes. Pattern use is justified when the axis of variation, extension frequency, testing needs, or behavioral complexity warrants the structure.
Design / research exercise¶
Take a conditional with at least four branches. Implement both a straightforward conditional version and a Strategy/State version. Define a change scenario under which each version is superior.
Suggested reading¶
- GoF: Strategy, Template Method, State, Command.