Example #1
0
File: demo.php Project: zrcing/APM
    {
        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 $flyBehavior)
    {
        $this->flyBehavior = $flyBehavior;
    }
}
class RubberDuck extends Duck
{
}
$duck = new RubberDuck();
$duck->setFlyBehavior(new FlyWithWings());
$duck->performFly();
$duck->setFlyBehavior(new FlyWithNo());
$duck->performFly();
Example #2
0
    {
        $this->flyBehavior = new FlyWithWings();
        $this->quackBehavior = new Quacks();
        $this->name = "红头鸭\n";
    }
}
class MallardDuck extends Duck
{
    public function __construct()
    {
        $this->flyBehavior = new FlyWithWings();
        $this->quackBehavior = new Squeak();
        $this->name = "绿头鸭\n";
    }
}
//---------------------------------------
//测试上面的代码
//---------------------------------------
$rubberDuck = new RubberDuck();
$redHeadDuck = new RedHeadDuck();
$mallardDuck = new MallardDuck();
//依次执行行为
$rubberDuck->display();
$rubberDuck->peformFly();
$rubberDuck->peformQuack();
//更改行为
$rubberDuck->setFlyBehavior(new FlyWithWings());
$rubberDuck->setQuackBehavior(new Quacks());
//执行更改后的行为
$rubberDuck->peformFly();
$rubberDuck->peformQuack();