Three approaches for decorating your code

Which implementation of the Decorator pattern is right for your code?

1 2 Page 2
Page 2 of 2
  • Pros:

    1. This type of implementation never changes the type of decorated object.
    2. We can write as many decorators as we need and add/remove them to/from a decorated object anytime.
    3. Every decorator implementation can be independent of others.
    4. After adding/removing decorator, we get the new behavior without any other changes.
    5. The implementation is a convenient way to follow the visual objects' style preferences.
  • Cons:

    1. Unfortunately, we cannot use this implementation for every object type. This implementation is based on decorated object callbacks (like Listeners) and other features we can use externally. In other words, we cannot use the external implementation if the decorated object doesn't have the appropriate features.
    2. For visual objects, for example, we cannot use this implementation if we need to change object painting (e.g., we cannot write RoundButton in this way).

The external type of Decorator implementation is easy to use and gives us good object-oriented design. But we can use it only if the decorated object has appropriate external features like Listeners, Borders, LayoutManagers, and pluggable look-and-feels.

Conclusion

After discussion about the three types of Decorator implementations we can compare them:

  • I don't see any case where using the inheritance type of implementation is sensible. It appears simple, but will prove difficult for extension and conflicts with object-oriented design principles. I recommend not using the inheritance implementation. As I noted above, the javax.swing.JButton was implemented this way. I hope the Swing division of Sun will redevelop Swing classes to remove this type of implementation.
  • The wrapper implementation provides good object-oriented design and works well for those classes with a limited method count. For longer classes, a programmer must choose the lesser of two evils: implement many wrapper methods and keep the type of decorated object or maintain a simple decorator implementation and sacrifice retaining the decorated object type. In many cases, using this implementation type proves difficult for visual objects.
  • The external implementation is easy to use and promotes good object-oriented design, but we can use it only if the decorated object has appropriate external features like Listeners, Borders, LayoutManagers, and pluggable look-and-feels. It works well for visual object decoration.
Michael Feldman's Java experience began in 1998. He develops frameworks and utilities and introduces design patterns to everyday development work.

Learn more about this topic

1 2 Page 2
Page 2 of 2