PHP 装饰器模式

2019-03-09  本文已影响0人  wyc0859

装饰器模式可以动态的添加修改类的功能,以传统编程模式不同的是,装饰器模式仅需在运行时添加一个装饰器对象即可实现最大的灵活性

装饰内容:传统编程模式

class A{
    public function show()
    {
        echo "<p style='color:red'>";
        echo '一行字';
        echo "</p>";
    }
}
$a=new A;
$a->show();  //红色的一行字

装饰内容:装饰器模式

use Server\Hua;
use Server\ColorDrawDecorator;

$hua=new Hua;
$hua->addDecorator(new ColorDrawDecorator);  //只需要简单的一行就可以添加装饰
$hua->show();
定义接口
namespace Server;
interface DrawDecorator{
    function beforeDraw();
    function afterDraw();
}
继承接口
namespace Server;
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>";
    }
}
定义装饰器
namespace Server;
class Hua{
    protected $decorators = array();
    function addDecorator(DrawDecorator $decorator)    {
        $this->decorators[] = $decorator;
    }
    function beforeDraw()    {
        foreach($this->decorators as $decorator)        {
            $decorator->beforeDraw();
        }
    }
    function afterDraw()    {
        $decorators = array_reverse($this->decorators);
        foreach($decorators as $decorator)        {
            $decorator->afterDraw();
        }
    }
    function show()    {
        $this->beforeDraw();
        echo '一行字';
        $this->afterDraw();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读