装饰器模式
- 装饰器模式,可以动态地添加修改类的功能
- 一个类提供了一项功能,如果要在修改并添加额外的功能,传统的编程模式,需要写一个子类继承它,并重新实现类的方法
- 使用装饰器模式,仅需在运行时添加一个装饰器对象即可实现,可以实现最大的灵活性。
示例代码:
- 声明一个装饰器的接口
<?php
namespace TT;
interface DrawDecorator
{
function beforeDraw();
function afterDraw();
}
2.画布
<?php
namespace TT;
class Canvas
{
protected $decorators;
function addDecorator(DrawDecorator; $decorator)
{
$this->decorators[] = $decorator;
}
function draw()
{
$this->beforeDraw();
// draw
$this->afterDraw();
}
function beforeDraw()
{
foreach($this->decorators as $decorator)
{
$decorator->beforeDraw();
}
}
function afterDraw()
{
// 反转,后进先出
$decorators = array_reverse($this->decorators);
foreach($decorators as $decorator)
{
$decorator->afterDraw();
}
}
}
- 装饰器实现代码
namespace TT;
class ColorDrawDecorator implements DrawDecorator
{
protected $color;
function __construct($color = 'red')
{
$this->color = $color;
}
function beforeDraw()
{
echo "<div style='color: {$this->color};'>";
}
function afterDraw()
{
echo "</div>";
}
}
- 调用
<?php
$canvas1 = new TT\Canvas();
$canvas1->init();
$canvas1->addDeCorator(new \TT\ColorDrawDecorator('green'));
$canvas1->rect(2, 6, 4, 12);
$canvas1->draw();