装饰模式之变形金刚
(1)抽象构建类Tansform
立即学习“PHP免费学习笔记(深入)”;
interface Transform
{
public function move();
}(2)具体构建类Car
立即学习“PHP免费学习笔记(深入)”;
final class Car implements Transform
{
public function __construct() {
echo '变形金刚是一辆汽车';
}
public function move() {
echo '在陆地上移动';
}
}
(3)抽象装饰类Changer
立即学习“PHP免费学习笔记(深入)”;
class Changer implements Transform
{
private $transform;
public function __construct($tansform='') {
$this->transform = $tansform;
}
public function move() {
$this->transform->move();
}
}(4)具体装饰类Root,Airplane
立即学习“PHP免费学习笔记(深入)”;
class Root extends Changer
{
public function __construct($tansform='') {
parent::__construct($tansform);
echo '变成机器人';
}
public function say() {
echo '说话';
}
}
class Airplane extends Changer
{
public function __construct($tansform='') {
parent::__construct($tansform);
echo '变成机飞机';
}
public function fly()
{
echo '在天空飞翔';
}
}(5)测试代码
立即学习“PHP免费学习笔记(深入)”;
$camaro = new Car(); echo '<br>'; $camaro->move(); echo '<br>'; echo '-----------'; echo '<br>'; $bumblebee = new Airplane($camaro); echo '<br>'; $bumblebee->move(); echo '<br>'; $bumblebee->fly(); echo '<br>'; echo '-----------'; echo '<br>'; $bumblebee = new Root($camaro); echo '<br>'; $bumblebee->move(); echo '<br>'; $bumblebee->say();
变形金刚是一辆汽车
在陆地上移动
-----------
变成机飞机
在陆地上移动
在天空飞翔
-----------
变成机器人
在陆地上移动
说话
以上就介绍了php 装饰模式,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。











