Thursday, August 23, 2012

Refactoring inheritence explosion to fleunt decorator

The decorator pattern is used to extend or alter the
functionality of an object at runtime. IT does this by wrapping the object with
a decorator class, leaving the original object intact without modification. Let’s
look into the code structure given below for a Starbucks coffee menu
implementation for calculating the cost of the beverages including the various
coffee toppings provided. An inheritance based approach will result in an
object explosion like this.

We can try to reduce the complexity of this design by
refactoring this to a decorator implementation. Later I’ll show how we can use
fluent interfaces to create a fluent decorator that is more readable and a
cleaner approach to use. The final
implementation changes our code structure to something like