UnstableFractal
UnstableFractal

Reputation: 1422

Am I using decorator pattern correctly?

I've got class A with some functionality:

class A < B {
    private some_data;
    public start() { ... };
}

Class B is a base-class for multiple classes like A. Nothing special, it inherits from class C.

abstract class C {
    abstract public start();
}

I've got an abstract decorator:

abstract class decoratorC < C {
    private C;
    public construct() {
        self->C->start();
    }
}

And a concrete decorator:

class ConcreteDecoratorForA < decoratorC {
    public start() {
        parent->start();
        // code here
    }
}

So the problem is: I need private properties and such from class A in a "code here" section AND functionality from class B as well.

I've got an architecture mistake somewhere, it may be obvious for a fresh look. Maybe I need to remake structure around class B.

Upvotes: 1

Views: 54

Answers (1)

Kenneth
Kenneth

Reputation: 28737

In theory a decorator should not access properties of the class it decorates. The idea of a decorator is to provide functionality on top of the normal behavior.

For example, you could have a class that sends an email. Then you'd have another class, the decorator, that first logs the message and then uses the decorated class to send the e-mail.

The reason that decorators shouldn't access properties from the class it decorates, is that it doesn't know which class it's decorating. In my example of e-mail and logging, you can imagine another layer in between (say security). So you would have the following structure:

Logging -> security -> send mail

Since the decorator implements the same interface as the decorated class, this chain can be constructed in any way you want.

If you want to access data from the class you decorated, you should make that data part of the contract (C in your example). If it's specific to a subclass, then a decorator won't work, because your class is not generic.

Upvotes: 1

Related Questions