vendredi 16 novembre 2018

When using the Decorator pattern, how do you decorate additional functionality in between the concrete definition of a function?

I'm trying to understand if I am using the Decorator pattern properly, or if another pattern would be better suited for a situation like this:

Without redefining my interface, I am unable to decorate a function because it's parent's definition prevents me from doing so. I'm not sure if my question is clear, so perhaps an example:

interface IFoo
{
    public function bar();
}

class ConcreteFoo implements IFoo
{
    public function bar()
    {
        echo "hello world!\n";
    }
}

abstract class Decorator implements IFoo
{
    public function __construct(IFoo $foo)
    {
        $this->foo = $foo;
    }

    public function bar()
    {
        $this->foo->bar();
    }
}

class BeautifulDecorator extends Decorator
{
    public function bar()
    {
        // I am unable to insert 'beautiful' between 'hello' and 'world' without redefining the bar() function again
        parent::bar();
    }
}

For the sake of simplicity, I am essentially unable to print out something like 'hello beautiful world' without actually redefining the bar function to do so.

Is there a way to do so with the Decorator pattern, or is there a different pattern that can be used?

Aucun commentaire:

Enregistrer un commentaire