DEV Community

Cover image for Strategy Pattern
Asadullah Ehsan
Asadullah Ehsan

Posted on

Strategy Pattern

Once upon a time...

Thinky was staring at his messy code, completely lost. "Why is everything so tangled up? Every time I change one thing, everything breaks!" 🤯

Nerdy, adjusting his glasses, smirked. "Ah, my dear Thinky, what you need is the Strategy Pattern!"

"Strategy what now?" 🤔

🤓 "It's a behavioral pattern, meaning it helps organize how objects interact. It lets you change an object's behavior without modifying its structure."

🤔 "Sounds useful, but how does it work?"

🤓 "Every entity has behaviors, right? But those behaviors can vary. Instead of hardcoding them inside the entity, we separate them into their own collection of behaviors. Then, we compose the entity with those behaviors dynamically."

🤔 "So, instead of an entity being a behavior, it just has a behavior?"

🤓 "Exactly! And since the behaviors are separate, we can swap them at runtime without touching the entity itself."

🤔 "Cool! But give me an example."

🤓 "Alright, let's talk ducks! 🦆

Ducks are expected to quack and fly.

But not all ducks are the same—some fly normally, some don’t fly at all, and some use rocket boosters! 🚀

Likewise, not all ducks quack the same way—some squeak, some fake-quack, and some don’t make a sound."

🤔 "So... how do we handle all that variety without a mess?"

🤓 "We encapsulate each behavior as a separate strategy:

A FlyBehavior interface with different implementations: FlyWithWings, NoFly, FlyWithRocket.

A QuackBehavior interface with implementations like QuackLoudly, Squeak, MuteQuack.

Then, each duck chooses its behavior dynamically at runtime instead of having everything hardcoded. Boom—Strategy Pattern! 💡"

🤔 "Whoa, that means I can add new behaviors without modifying existing code?"

🤓 "Bingo! Now, if you ever need a TeleportingDuck, you just add a new TeleportBehavior—without touching anything else!"

🤔 "This is amazing! I'll keep an eye out for cases where I can use it."

🤓 "Good thinking, Thinky! Now, let’s see what others have to say about our discussion!"

📢 Inspired by Head First Design Patterns. Let us know your thoughts! 🚀

Check out the code here!

Top comments (0)