September 2016
Intermediate to advanced
270 pages
5h 16m
English
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 ...Read now
Unlock full access