Monday, April 13

Pattern of the Day

One pattern. Five minutes. Every day.

behavioralbeginner

Strategy

Define a family of algorithms, encapsulate each one, and make them interchangeable

Simple explanation

You want to travel to work. You can take a car, bus, or bike. The destination stays the same, but the way you get there changes. Each transportation method is a different strategy. You pick the best one depending on the weather and how much time you have.

Payment Methods

"A store accepts multiple payment methods: credit card, debit card, or PayPal. The checkout process is the same, but the actual payment algorithm differs. The store doesn't care how you pay—it just needs a payment strategy that works."

Use it when

  • You have multiple ways to solve a problem and need to select at runtime
  • You want to avoid conditional statements (if/else or switch) scattered throughout code

Today's question

How does Strategy differ from State pattern?

#interchangeable#algorithms#runtime-selection#encapsulation