Rocket Science Made Simple: Mastering Strategy Pattern with Rocket Behaviors

1. Inheritance is Not Rocket Science (But Still a Problem)
Imagine you're building a simulation of rockets. You start with a Rocket
superclass and create subclasses like CargoRocket
, WarRocket
, and ExplorerRocket
But soon you realize different rockets fly differently. One uses boosters, another uses ion propulsion, and one even glides. Modifying each subclass means code duplication or fragile inheritance trees.
2. Interfaces Alone Can't Handle This Orbit
You try separating flying behavior into an interface:
Then implement it in rockets. But now each rocket has to implement a unique fly behavior. Still messy. You’re repeating logic and scattering behavior everywhere.
3. Design Principle: Identify What Varies
We notice that flying behavior varies, but launching doesn’t. So we extract flying behavior:
"Identify the aspects that vary and separate them from what stays the same."
This leads us to the Strategy Pattern.
4. The Strategy Pattern: A Rocket-Smart Move
We encapsulate flying algorithms into separate strategy classes:
Then inject the behavior into our Rocket
5. Adding New Rocket Behaviors? Just Plug and Play
Need an eco-friendly rocket with solar sail? Add a new strategy:
No need to touch the Rocket
class and violate open/closed principle. Just plug in the new strategy:
6. Strategy Pattern Simplified
Definition: Strategy Pattern is a design pattern that lets you define a family of interchangeable algorithms, encapsulate each one in a separate class, and make them interchangeable in the object that uses them.
What Problem It Solves: When a class has multiple behaviors that may vary independently (like different flying styles of rockets), hardcoding or subclassing becomes messy and rigid.
How It Solves It: It separates the varying behavior (e.g., flying style) into individual strategy classes and uses composition to inject them into the main class (e.g., Rocket
). This makes the behavior interchangeable at runtime and easier to extend or modify without altering the core class.
7. Recap
The Strategy Pattern lets us:
Swap behaviors at runtime
Isolate variable logic
Scale new algorithms easily
Subscribe to my newsletter
Read articles from Vijay directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
