Skip to main content

Definition

“Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern lets the algorithm vary independently of the clients that use it”

Explanation

You design a common Strategy interface (for example, CompressionStrategy) and implement multiple concrete strategies (e.g. ZipCompression, RarCompression). A context class holds a reference to a strategy and delegates to it. At runtime the client picks and switches strategies as needed, without changing the context’s code.

Code

In the code below, Context uses different sorting strategies (ConcreteStrategyA and ConcreteStrategyB) to sort data.

Analogy

A food cart where you can choose how to cook. E.g., making a burger with different patties: you change the cooking algorithm (grill vs fry vs veggie) but the steps (assemble bun, toppings) remain the same. Another example is choosing an encryption algorithm: the same plaintext, different ciphers.

Interview Insights

Common uses: When multiple ways exist to do a task (sorting, compression, encryption) and you want to switch among them dynamically. Used in UI (different rendering modes), data processing (choosing filters), AI (choosing heuristic at runtime) etc.
Advantages: Promotes open/closed principle: new strategies can be added without changing existing code. Eliminates conditional statements for choosing algorithms. Achieves loose coupling between context and algorithm
Disadvantages: May introduce many small classes for each strategy. Clients must be aware of all strategy options and choose appropriately. Can be overkill if only one or two strategies exist.\

When to use Strategy vs. State?

How to implement adding new strategies (e.g. with factory or registry)?

Advantages over using if/else or switch?

Show how you’d code a strategy in your language (e.g. duck flying behaviors)