Hi 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
Joined: Aug 10, 2001
(a) Yes, at least as far as not making methods either final or private goes... (b) Yes, an Interface is usually best. Kyle
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.