装饰器模式
Posted 果然朝辉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器模式相关的知识,希望对你有一定的参考价值。
定义:可以动态地添加修改类的功能解析:一个类提供了一项功能,如果要在修改并添加额外的功能,传统的编程模式,需要写一个子类继承它,并重新实现类的方法。使用装饰器模式,仅需在运行时添加一个装饰器对象即可实现,可以实现最大的灵活性。
$canvas1 = new IMooc\Canvas();
$canvas1->init();
$canvas1->addDecorator(new \IMooc\ColorDrawDecorator(‘green‘));
$canvas1->addDecorator(new \IMooc\SizeDrawDecorator(‘16px‘));
$canvas1->rect(3,6,4,12);
$canvas1->draw();
<?php
namespace IMooc;
class Canvas
{
public $data;
protected $decorators = array();
function init($width = 20, $height = 10)
{
$data = array();
for ($i = 0; $i < $height; $i++)
{
for ($j = 0; $j < $width; $j++)
{
$data[$i][$j] = ‘*‘;
}
}
$this->data = $data;
}
function addDecorator(DrawDecorator $decorator)
{
$this->decorators[] = $decorator;
}
function beforeDraw()
{
foreach ($this->decorators as $decorator)
{
$decorator->beforeDraw();
}
}
function afterDraw()
{
$decorators = array_reverse($this->decorators);
foreach ($this->decorators as $decorator)
{
$decorator->afterDraw();
}
}
function draw()
{
$this->beforeDraw();
foreach ($this->data as $line)
{
foreach ($line as $char)
{
echo $char;
}
echo "<br/>\n";
}
$this->afterDraw();
}
function rect($a1, $a2, $b1, $b2)
{
foreach ($this->data as $k1 => $line)
{
if ($k1 < $a1 or $k1 > $a2) continue;
foreach ($line as $k2 => $char)
{
if($k2 < $b1 or $k2 > $b2) continue;
$this->data[$k1][$k2] = ‘ ‘;
}
}
}
}<?php
namespace IMooc;
interface DrawDecorator
{
function beforeDraw();
function afterDraw();
}<?php
namespace IMooc;
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
namespace IMooc;
class SizeDrawDecorator implements DrawDecorator
{
protected $size;
function __construct($size = ‘14px‘)
{
$this->size = $size;
}
function beforeDraw()
{
echo "<div style=‘font-size:{$this->size}‘";
}
function afterDraw()
{
echo "</div>";
}
}
以上是关于装饰器模式的主要内容,如果未能解决你的问题,请参考以下文章