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();
}
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());
}
}
Why use an interface?
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…