Tutorials Design Patterns Mastery

Strategy Pattern: Swappable algorithms at runtime

On this page

The Strategy Pattern

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from the clients that use it. This is the #1 tool for eliminating 100-line if/else blocks used for selecting logic.

1. Scenario: Payment Selection

A user can pay via CreditCard, PayPal, or Bitcoin. Instead of one giant Process() method, you create three Strategy classes.

public interface IPaymentStrategy 
{
    void Pay(decimal amount);
}

// THE CLIENT (Context)
public class CheckoutProcess 
{
    private IPaymentStrategy _strategy;
    
    public void SetStrategy(IPaymentStrategy s) => _strategy = s;

    public void Checkout(decimal amount) => _strategy.Pay(amount);
}

2. Why use it?

It follows the Open/Closed Principle. Next year, when the marketing team wants to add "Pay with Reward Points," you don't edit your existing checkout logic. You just create a new RewardPointStrategy class. The core system remains stable and untouched.

4. Interview Mastery

Q: "How is the Strategy pattern different from Dependency Injection?"

Architect Answer: "They are highly complementary. **Dependency Injection** is the *Mechanism* we use to get the strategy into the class. The **Strategy Pattern** is the *Architectural Design* of having multiple swappable implementations of an interface to handle different business rules. Strategy defines the 'Shape' of the solution; DI is the 'Plumbing' that connects it."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns Mastery
Course syllabus
1. Introduction to Design Patterns
2. Creational Patterns
3. Structural Patterns
4. Behavioral Patterns
5. Modern Enterprise & Cloud Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details