Skip to content

Instantly share code, notes, and snippets.

@ke-bab
Last active January 19, 2018 09:55
Show Gist options
  • Save ke-bab/06693ed559e4d49d3083c717c163fb28 to your computer and use it in GitHub Desktop.
Save ke-bab/06693ed559e4d49d3083c717c163fb28 to your computer and use it in GitHub Desktop.
PHP pattern "strategy" example, with ducks
// from "Head First Design Patterns by Eric Freeman"
interface FlyBehavior
{
public function fly();
}
class FlyWithWings implements FlyBehavior
{
public function fly() {
echo 'i`m flying', PHP_EOL;
}
}
class FlyNoWay implements FlyBehavior
{
public function fly() {
echo 'i can`t fly', PHP_EOL;
}
}
// base class
class Duck
{
public $flyBehavior;
public function performFly() {
$this->flyBehavior->fly();
}
public function setFlyBehavior($fb) {
$this->flyBehavior = $fb;
}
public function swim() {
echo 'i swim', PHP_EOL;
}
}
class MallardDuck extends Duck
{
public function __construct() {
$this->flyBehavior = new FlyWithWings();
}
}
class RubberDuck extends Duck
{
public function __construct() {
$this->flyBehavior = new FlyNoWay();
}
}
// check it
echo 'i`m mallard duck', PHP_EOL;
$mallard = new MallardDuck();
$mallard->performFly();
$mallard->swim();
echo PHP_EOL;
echo 'i`m rubber duck', PHP_EOL;
$rubber = new RubberDuck();
$rubber->performFly();
$rubber->swim();
// dynamic behavior change
echo PHP_EOL;
$mallard2 = new MallardDuck();
$mallard2->performFly();
$mallard2->setFlyBehavior(new FlyNoWay);
$mallard2->performFly();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment