<?php include_once 'pattern/Duck.php'; $obj = new RubberDuck(); $obj->display();
{ $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();