装饰者模式(Decorator Pattern)
- 装饰者模式允许向一个现有的对象添加新的功能,同时又不改变其结构
- 如果要修改并添加一个类中额外的功能,传统的编程模式需要写一个子类继承它,并重新实现类的方法
- 使用装饰者模式,仅需在运行时添加一个装饰器对象即可实现,可以实现最大的灵活性
IDecorator接口
interface IDecorator
{
public function beforeDo();
public function afterDo();
}
需要改进的类
<?php
namespace core;
class DecoratorPattern
{
public $name;
protected $decorators = []; // 存放装饰器
public function __construct($name)
{
$this->name = $name;
}
// 增加装饰器
public function addDecorator(IDecorator $decorator)
{
$this->decorators[] = $decorator;
}
public function beforeDo()
{
foreach ($this->decorators as $decorator) {
$decorator->beforeDo();
}
}
public function afterDo()
{
// 反转数组,先进后出
$decorators = array_reverse($this->decorators);
foreach ($decorators as $decorator) {
$decorator->afterDo();
}
}
public function echoName()
{
$this->beforeDo();
echo $this->name;
$this->afterDo();
}
}
颜色装饰器类
<?php
namespace core;
class ColorDecorator implements IDecorator
{
protected $color;
public function __construct($color = 'red')
{
$this->color = $color;
}
public function beforeDo()
{
echo "<p>颜色即将更改为:{$this->color}</p>";
echo "<div style='color: {$this->color}'>";
}
public function afterDo()
{
echo "</div>";
echo "<p>颜色已更改为:{$this->color}</p>";
}
}
实现
$descrator1 = new \core\DecoratorPattern("小明");
$descrator1->addDecorator(new \core\ColorDecorator('green')); // 添加绿色装饰者
$descrator1->addDecorator(new \core\ColorDecorator('red')); // 添加红色装饰者
$descrator1->addDecorator(new \core\ColorDecorator('blue')); // 添加蓝色装饰者
$descrator1->echoName();
结果