Strategy design pattern

The Strategy design pattern exists to allow us to alter the behavior of an object at runtime.

Let's suppose we have a class that will raise a number to a power, but at runtime we want to alter whether we square or cube a number.

Let's start off by defining an interface a function that will raise a number to a given power:

<?php 
 
interface Power 
{ 
  public function raise(int $number): int; 
} 

We can accordingly define classes to Square and also Cube a given number by implementing the interface.

Here's our Square class:

<?php 
 
class Square implements Power 
{ 
  public function raise(int $number): int 
  { 
    return pow($number, 2); 
  } 
} 

And let's define our Cube class:

<?php class Cube implements Power { public function raise(int $number): int ...

Get Mastering PHP Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.