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:

  1. 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.
  2. 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.
🩷
I love sharing free content to help fellow developers. Your support means a lot! Please follow me on LinkedInGitHub, and Twitter.
Let's connect and grow together! πŸš€

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!

πŸ’‘
Have a question you'd love answered?
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

Subscribe to Coding With Vera

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe