1.装饰器模式(Decorator),可以动态地添加修改类的功能
2.一个类提供了一项功能,如果要在修改并添加额外的功能,传统的编程模式,需要写一个子类继承它,并重新实现类的方法
3.使用装饰器模式,仅需在运行时添加一个装饰器对象即可实现,可以实现最大的灵活性

<?php

namespace Lib;

interface Decorator
{
    public function before();

    public function after();
}
<?php


namespace Lib;

class Draw
{
    protected $decorator;

    public function pencil()
    {
        $this->beforePencil();

        echo "我是装饰器";

        $this->afterPencil();
    }

    public function addDecorator($decorator)
    {
        $this->decorator[] = $decorator;
    }

    public function beforePencil()
    {
        if($this->decorator)
        {
            foreach ($this->decorator as $decorator)
            {
                $decorator->before();
            }
        }

    }

    public function afterPencil()
    {
        if($this->decorator)
        {
            $tmp = array_reverse($this->decorator);
            foreach ($tmp as $decorator) {
                $decorator->after();
            }
        }
    }

}
<?php

namespace Lib;

class ColorDecorator implements \Lib\Decorator
{

    public function before()
    {
        // TODO: Implement before() method.

        echo "画上颜色";
    }

    public function after()
    {
        // TODO: Implement after() method.
    }

}
$draw = new \Lib\Draw();

$colorDecorator = new \Lib\ColorDecorator();

$draw->addDecorator($colorDecorator);
$draw->pencil();

results matching ""

    No results matching ""

    results matching ""

      No results matching ""