Decorator

Intent

Attach additional responsibilities to an object dynamically.  Decorators provide a flexible alternative to subclassing for extending functionality.

      -Design Patterns, GoF

 

Being somewhat of a closet Luddite, I only recently purchased my first cell phone.  My phone is faceplate-ready – in other words, I can snap on a stylish faceplate.  As far as I can tell, faceplates are the only dynamically changeable aspect of my cell phone.  For example, I cannot snap on antennas or speakers; those are set statically at the factory.

      -JavaWorld, December, 2001

 

Questions

1) How is a Decorator an alternative to static inheritance?  What makes it better or worse?

2) What is the relationship between the Decorator and the Decoratee?

3) What is the difference between an Adapter and a Decorator?  Why are both also known as “Wrappers”?

4) What is the implication of Decorators on performance?

5) How is the Decorator instantiated? 

6) Why must a Decorator conform to the component interface?  Would a generic wrapper be just as good?

7) How do you know if a Decorator can mix with another Decorator?

8) Is it essential that the Decorator interface be different than the Concrete class interface?

 

Examples – Which are Decorators?

1) Swing Table Model

2) Java IO, e.g. FileReader, LineNumberReader, etc.

 

Implement It!

Imagine you need to build a component to calculate the price of a widget.  The widget’s retail price is $500, but a number of different discounts could be applied.  If the customer is over 50 years old, then take %10 off.  If the customer is from NY, add $10.  If the date is after October 1st, mark it down 20%.  Implement this using the Decorator pattern, and given the following context object (ignore the horrible encapsulation!):

     

      public class Order {

            public int customerAge;

            public String customerState;

            public Date orderDate;

      }

 

Is this an appropriate or inappropriate use of this pattern?  What design might be better.

 

References

·   Decorate your Java Code, David Geary (Javaworld, Dec 2001)

·   Using the Decorator Pattern, Budi Kurniawan (OnJava.com, Feb 2003)