Iterative alternative to decorators

design-patterns

So decorators wrap a base class recursively, right? And have a single super class object which is at the "core" class.

Couldn't you just add an ArryList/LinkedList of decorations in the "core" class and achieve the same thing? This would avoid recursion (which is expensive), but allow the dynamic behavior of being able to "decorate" your classes.

Is this a different pattern or an alternative version of decorators or something else?

Ex:

Decorator

Beverage class
  getDescription(){blah}
  cost();

HouseBlend inherits from Beverage
  cost(){2.99}

CondimentDecorator inherits from Beverage
  Beverage bev;
  cost(){.19 + bev.cost}
  getDescription{blah}

VS

Other?

Beverage class
  getDescription(){blah}
  cost();

HouseBlend inherits from Beverage
  List<Beverage> condiments      
  cost(){2.99 + iterative condiments}

CondimentDecorator inherits from Beverage
  cost(){blah}
  getDescription{blah}

It seems like the decorator might be a little more flexible, but the other version would allow you to keep track of specific instances of items. Also, if you had espresso you could have a double shot, where with a pure decorator that would be hard.

Best Answer

The reason the decorator pattern works the way it does is because it aims at allowing subclassing-style functionality at runtime instead of compiletime. This is relevant since your alternative requires modification of HouseBlend at compiletime. This is something that the decorator pattern was explicitly designed to avoid.

In my experience, the decorator pattern is typically used when you get a binary component that exposes Beverage and a bunch of subclasses (such as HouseBlend) that you cannot modify. In this case, the decorator enables you to still modify the way those subclasses behave in a transparent way.

If you have access to Beverage and/or HouseBlend and can modify and recompile them, a host of alternative design options become available, including the one you propose.

Related Topic