C++ Decorator Pattern – Using the Decorator Pattern in a Deep Class Hierarchy

cdesign-patterns

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?

Best Answer

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.

Related Topic