<?php
interface
FlyBehavior{
public
function
fly();
}
class
FlyWithWings
implements
FlyBehavior{
public
function
fly(){
echo
"Fly With Wings
"
;
}
}
class
FlyWithNo
implements
FlyBehavior{
public
function
fly(){
echo
"Fly With No Wings
"
;
}
}
class Duck{ private $_flyBehavior ; public function performFly(){ $this ->_flyBehavior->fly(); } public function setFlyBehavior(FlyBehavior $behavior ){ $this ->_flyBehavior = $behavior ; } } class RubberDuck extends Duck{ } |
// Test Case
$duck
=
new
RubberDuck();
/* 想让鸭子用翅膀飞行 */
$duck
->setFlyBehavior(
new
FlyWithWings());
$duck
->performFly();
/* 想让鸭子不用翅膀飞行 */
$duck
->setFlyBehavior(
new
FlyWithNo());
$duck
->performFly();