I am a very beginning in PHP and Design Patterns. I have been studying the amazing Head First Design patterns. So, I have been trying to translate the original into PHP. The class is working well, however, I would like to ask:
Is this considered good PHP?
Someone mentioned that this is not a Strategy Pattern. Head First's definition: "Strategy lets the algorithm vary independently from clients that use it". Is this not correct?
<?php
interface FlyBehavior{
public function fly();
}
class FlyWithWings implements FlyBehavior{
public function fly(){
echo "I am flying!<br>";
}
}
class FlyNoWay implements FlyBehavior{
public function fly(){
echo "I cannot fly!";
}
}
interface QuackBehavior{
public function quack();
}
class QuackQuack implements QuackBehavior{
public function quack(){
echo "Quack<br>";
}
}
class MuteQuack implements QuackBehavior{
public function quack(){
echo "Silence";
}
}
class Squeak implements QuackBehavior{
public function quack(){
echo "Squeak";
}
}
abstract class Duck{
protected $quackBehavior;
protected $flyBehavior;
public function performQuack(){
$this->quackBehavior->quack();
}
public function performFly(){
$this->flyBehavior->fly();
}
abstract public function display();
public function swim(){
echo "All ducks float, even decoy";
}
}
class MallardDuck extends Duck{
public function __construct(){
$this->quackBehavior=new QuackQuack();
$this->flyBehavior=new FlyWithWings();
}
public function display(){
echo "I am real Mallard duck!";
}
}
$mallard=new MallardDuck();
$mallard->performQuack();
$mallard->performFly();
?>
fly
function inside ofFlyWithWings
but never creates it inside of the Duck Class. \$\endgroup\$