Course contentsShow
← Software Engineering
Lesson 314 of 1,9339. Behavioral Design PatternsFree lesson

Implementing Strategy with Composition

Build Strategy pattern using composition to inject different behaviors into a context object at construction or runtime.

Implementing Strategy with Composition

What you'll learn: How to use composition to inject different algorithm implementations into a context object, enabling runtime behavior changes.

The Core Idea

The Strategy pattern works by giving a context object a reference to a strategy object that implements a specific algorithm. Instead of the context containing all possible algorithms internally (via inheritance or conditional logic), it delegates the algorithmic work to whichever strategy object you've composed it with.

Think of it like hiring a consultant: your company (the context) doesn't need to know every specialty—you just bring in the right expert (strategy) for each job. You can even swap consultants mid-project if needs change.

Composition in Action

Composition means the context has-a strategy, not is-a strategy. You pass the strategy object to the context, typically through:

  • Constructor injection: Pass the strategy when creating the context
  • Setter method: Change the strategy after construction (runtime flexibility)

The context calls a method on the strategy interface whenever it needs to execute the algorithm, completely unaware of which concrete implementation it's using.

Why This Matters

By composing strategies into the context:

  1. Decoupling: Context doesn't know implementation details
  2. Flexibility: Switch algorithms without changing context code
  3. Runtime changes: Modify behavior dynamically as conditions change
  4. Testability: Inject mock strategies for testing

This is the "how" that makes Strategy powerful—the context becomes a flexible shell that adapts its behavior based on which strategy you've plugged into it.

Key Takeaway: Strategy pattern uses composition to inject algorithm objects into a context, allowing you to select or swap behaviors at construction or runtime without modifying the context itself.