PHP
The Strategy pattern
Learn the Strategy pattern that packages interchangeable algorithms at runtime.
What does the Strategy pattern do?
The Strategy pattern packages algorithms that share a goal but behave differently. For example, a payment step can have credit card, bank transfer and cash as different strategies.
All strategies implement a common Algorithm interface. A Context class knows which strategy to use; the client only talks to Context. The strategy can be swapped at runtime, so behavior stays flexible without touching the class hierarchy.
Concrete strategies and Context.run
Each concrete strategy implements the Algorithm interface and writes its behavior in compute. For example, ConcreteStrategyA can return 'Result A' and ConcreteStrategyB 'Result B'.
The Context class takes an Algorithm instance in its constructor and calls its compute method inside run. The client runs Context without knowing which concrete class is in use.
Exercise Implement Strategy and print the result
Write an Algorithm interface (with a compute(): string method). ConcreteStrategyA returns 'Result A'. Write a Context class that takes an Algorithm in its constructor and calls compute inside run, returning the result. Give the A strategy to Context and print the result via run.
Show example solution
string; }. ConcreteStrategyA returns 'Result A'. Context takes Algorithm in constructor, run calls compute and returns. Run with new Context(new ConcreteStrategyA()), print ->run().
Example solution:
<?php
interface Algorithm {
public function compute(): string;
}
class ConcreteStrategyA implements Algorithm {
public function compute(): string { return 'Result A'; }
}
class ConcreteStrategyB implements Algorithm {
public function compute(): string { return 'Result B'; }
}
class Context {
public function __construct(private Algorithm $algo) {}
public function run(): string { return $this->algo->compute(); }
}
$c = new Context(new ConcreteStrategyA());
echo $c->run();
Test yourself
-
What does the Strategy pattern provide?
- Swapping the algorithm at runtime
- Extending the class through inheritance
- Guaranteeing a single instance
- Compatibility with an external system
Show answer
Swapping the algorithm at runtime — Correct. Strategy lets you swap the algorithm at runtime.
-
The interface the Context holds
<?php
class Context {
public function __construct(private ____ $algo) {}
public function run(): string { return $this->algo->compute(); }
}
Show answer
<?php
class Context {
public function __construct(private Algorithm $algo) {}
public function run(): string { return $this->algo->compute(); }
}
-
Match the Strategy concepts
- Algorithm
- the interface
- Context
- holds the strategy
- ConcreteStrategyA
- concrete strategy A
- run
- applies the strategy
Next lesson: The Decorator pattern