Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
Looks like I didn't remember the pattern correctly. You're right: they must implement the same interface, not inherit from one another! –  pwny Feb 16 '12 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 Feb 16 '12 at 20:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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