3

How would one use the Decorator design pattern for anything other than trivial toy problems, in a deep class hierarchy? For example, let's say you have the class

class Decorated
: public Foo, Bar, Baz
{
public:
  void operation();
};

You would decorate it like this

class Decorator
: public Decorated
{
  void operation() { d.operation(); }
private:
  Decorated d;
};

The issue I'm having is that Decorated can have many inherited methods (from Foo, Bar and Baz) and the Decorator needs to "redirect" them all to its inner object or the object's state will be split between the decorator and the decorated object. How can one make sure the a Decorator correctly decorates another object and that no methods are called on the decorator instead of the decorated?

1 Answer 1

4

A solution is to define a common interface that both Decorator and Decorated must implement. This interface should contain all the methods that must be decorated.

Additionally, Decorator must not be a subclass of Decorated, so that nothing is inherited from Decorated and Decorator must provide its own implementation for each method in the interface.

It is OK to have an instance of Decorated as a member variable of Decorator (strong aggregation): Decorator redirects all method calls to Decorated, as appropriate.

2
  • Looks like I didn't remember the pattern correctly. You're right: they must implement the same interface, not inherit from one another!
    – anthonyvd
    Commented Feb 16, 2012 at 20:11
  • If you want to decorate methods that Decorated inherits from its super-classes, I would define an interface that also the super-classes must implement.
    – Giorgio
    Commented Feb 16, 2012 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.