The Strategy Pattern
How can you avoid making massive objects that can do anything but are not scalable? You can encapsulate the behaviors and make them interchangeable using the strategy pattern featured in this week's post.
Situation
You're ready to add a new feature to the code!
Task:
Add the ability for a Bird π¦ to swim.
Current Situation:
- The Bird can already fly.
Options:
- Add Swimming to the Bird:
If you want the Bird to swim, add 'swim' to its abilities.
Problem: Now the Bird can both fly and swim, which makes it redundant. It's not scalable. - Create a New Swimmer Object:
Keep swimming separate from the Bird. This avoids turning it into a "merm-bird" and keeps things clean and scalable.
Strategy Pattern
To implement this, we should focus on the Bird's functionality, specifically on how it travels.
We want the Bird to be able to switch between flying and swimming.
Both of these are strategies for travel, so instead of adding both abilities directly to the Bird, we can make these strategies interchangeable.
This is where the strategy pattern comes into play.
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it [1].
This means you can switch the Bird's travel method without changing the Bird itself. The strategy pattern enables the travel method to vary independently from the Bird, making the design more flexible and scalable.
Solution
The strategy pattern lets us make travel methods interchangeable. We can create a Travel
protocol and have both flying and swimming follow it.
Here's how it looks in a diagram:
Conclusion
In conclusion, to add swimming to our Bird π¦ without making it a "merm-bird," we should use the strategy pattern.
This approach makes travel methods like flying and swimming interchangeable, keeping our design clean and scalable.
By creating a Travel
protocol, both flying and swimming can implement it, allowing the Bird to switch between them seamlessly.
This way, we enhance the Bird's abilities without complicating its design, ensuring flexibility and simplicity in our code.
Thank you for reading!
Email me at [email protected] for a chance to be featured in my next article!
References
[1] Strategy Pattern: Design Patterns: Elements of Reusable Object-Oriented Software (1994) by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides page 315