Last active
January 19, 2018 09:55
-
-
Save ke-bab/06693ed559e4d49d3083c717c163fb28 to your computer and use it in GitHub Desktop.
PHP pattern "strategy" example, with ducks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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