如何在PHP中实现装饰器?

2022-08-30 13:47:40

假设有一个名为 “” 的类,它有一个名为 “” 的成员函数。Class_Afunc

我希望“”通过包装在装饰器类中来做一些额外的工作。funcClass_A

$worker = new Decorator(new Original());

有人能举个例子吗?我从来没有在PHP中使用过OO。

以下版本是否正确?

class Decorator
{
    protected $jobs2do;

    public function __construct($string) {
        $this->jobs2do[] = $this->do;
    }

    public function do() {
        // ...
    }
}

上面的代码打算给数组一些额外的工作。


答案 1

我建议你也为装饰器和你想要装饰的对象创建一个统一的接口(甚至是一个抽象的基类)。

要继续上面的示例,您可以像这样:

interface IDecoratedText
{
    public function __toString();
}

然后当然修改两者并实现接口。TextLeetText

class Text implements IDecoratedText
{
...//same implementation as above
}

class LeetText implements IDecoratedText
{    
    protected $text;

    public function __construct(IDecoratedText $text) {
        $this->text = $text;
    }

    public function __toString() {
        return str_replace(array('e', 'i', 'l', 't', 'o'), array(3, 1, 1, 7, 0), $this->text->toString());
    }

}

为什么使用接口?

因为这样,您可以根据需要添加任意数量的装饰器,并确保每个装饰器(或要装饰的对象)将具有所有必需的功能。


答案 2

这很容易,特别是在像PHP这样的动态类型语言中:

class Text {

    protected $string;

    /**
     * @param string $string
     */
    public function __construct($string) {
        $this->string = $string;
    }

    public function __toString() {
        return $this->string;
    }
}

class LeetText {

    protected $text;

    /**
     * @param Text $text A Text object.
     */
    public function __construct($text) {
        $this->text = $text;
    }

    public function __toString() {
        return strtr($this->text->__toString(), 'eilto', '31170');
    }
}

$text = new LeetText(new Text('Hello world'));
echo $text; // H3110 w0r1d

您可能也想看看维基百科的文章


推荐