Concept Flow - Strategy pattern
Client code
Choose strategy
Set strategy object
Call strategy method
Strategy executes algorithm
Return result to client
The client picks a strategy object, sets it, then calls its method to run the chosen algorithm.
<?php interface Strategy { public function doOperation(int $a, int $b): int; } class AddStrategy implements Strategy { public function doOperation(int $a, int $b): int { return $a + $b; } } class Context { private Strategy $strategy; public function __construct(Strategy $strategy) { $this->strategy = $strategy; } public function executeStrategy(int $a, int $b): int { return $this->strategy->doOperation($a, $b); } } $addStrategy = new AddStrategy(); $context = new Context($addStrategy); echo $context->executeStrategy(5, 3); // Outputs 8 ?>
| Step | Action | Object/Variable | Value/Result | Explanation |
|---|---|---|---|---|
| 1 | Create AddStrategy object | $addStrategy | AddStrategy instance | AddStrategy object created to perform addition |
| 2 | Create Context with AddStrategy | $context | Context instance with AddStrategy | Context stores the strategy object |
| 3 | Call executeStrategy(5, 3) | executeStrategy | Calls AddStrategy->doOperation(5,3) | Context delegates operation to strategy |
| 4 | AddStrategy->doOperation(5,3) | doOperation | 8 | AddStrategy adds 5 + 3 and returns 8 |
| 5 | executeStrategy returns | executeStrategy | 8 | Context returns the result from strategy |
| 6 | echo output | Output | 8 | Program prints 8 to the screen |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|---|
| $addStrategy | null | AddStrategy instance | AddStrategy instance | AddStrategy instance | AddStrategy instance | AddStrategy instance |
| $context | null | null | Context instance with AddStrategy | Context instance with AddStrategy | Context instance with AddStrategy | Context instance with AddStrategy |
| Result | null | null | null | null | 8 | 8 |
Strategy pattern lets you choose an algorithm at runtime. Define a Strategy interface with a method. Create concrete Strategy classes implementing the interface. Context holds a Strategy object and calls its method. Change strategy to change behavior without changing Context.