File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes OO, Patterns, UML and Refactoring and the fly likes Decorator in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Decorator in Java " Watch "Decorator in Java " New topic

Decorator in Java

Graham Mead
Ranch Hand

Joined: Sep 28, 2001
Posts: 57
As a relative newcomer to patterns I would appreciate any 'experienced' comments concerning some queries I have on the Decorator pattern.
a) As the concrete component subclasses the same class (or inherits the same interface)as the decorator does this imply that to implement this pattern without code changes to the concrete class you must design your concrete class knowingthat it will be deocorated.
b) As Java doesn't support multiple inheritance and any pre-existing concrete classes may already be inheriting from another, does this mean that the decorator pattern is best implemented with the top level component class as an interface.
Thank you to anyone who responds.
Graham Mead
Kyle Brown
Ranch Hand

Joined: Aug 10, 2001
Posts: 3892
(a) Yes, at least as far as not making methods either final or private goes...
(b) Yes, an Interface is usually best.

Kyle Brown, Author of Persistence in the Enterprise and Enterprise Java Programming with IBM Websphere, 2nd Edition
See my homepage at for other WebSphere information.
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
It can sometimes be hard or clumsy to "decorate" existing classes which you don't have the source code. It's rarely actually impossible, though. The Decorator should only need to "decorate" the public methods of the decorated object, and by definition these are available for use by the Decorator.
If it requires a lot of code, and/or duplication of the internals of another class to decorate it, then that should be treated as a "code smell" that the decorated class is in need of a spot of refactoring.
This is another good reason for avoiding the nameless "package" scope for your methods, too. If you make use of "package" scope, then the Decorator probably has to be in the same package as the decorated class, which seems a needless restriction.

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
I agree. Here's the link:
subject: Decorator in Java
It's not a secret anymore!