问题描述
假设有一个名为"Class_A
"的类,它具有一个名为"func
"的成员函数.
Suppose there is a class called "Class_A
", it has a member function called "func
".
我希望"func
"通过将Class_A
包装在装饰器类中来做一些额外的工作.
I want the "func
" to do some extra work by wrapping Class_A
in a decorator class.
$worker = new Decorator(new Original());
有人可以举一个例子吗?我从未在PHP中使用OO.
Can someone give an example? I've never used OO with PHP.
以下版本正确吗?
class Decorator
{
protected $jobs2do;
public function __construct($string) {
$this->jobs2do[] = $this->do;
}
public function do() {
// ...
}
}
上面的代码旨在为数组增加一些额外的工作.
The above code intends to put some extra work to a array.
推荐答案
我建议您还为装饰器和要装饰的对象创建一个统一的接口(甚至是抽象基类).
I would suggest that you also create a unified interface (or even an abstract base class) for the decorators and the objects you want decorated.
要继续上述示例,请提供以下内容:
To continue the above example provided you could have something like:
interface IDecoratedText
{
public function __toString();
}
然后当然要修改 和Text
来实现该接口.
Then of course modify both Text
and LeetText
to implement the interface.
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());
}
}
为什么要使用界面?
因为这样您可以添加任意数量的装饰器,并确保每个装饰器(或要装饰的对象)将具有所有必需的功能.
Because then you can add as many decorators as you like and be assured that each decorator (or object to be decorated) will have all the required functionality.
这篇关于如何在PHP中实现装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!