Impementing the Decorator Pattern for a large super class
Say I want to make some JComponents that change colour when the mouse cursor is within their bounds. I'd like to do this for several components, so I'd probably use the decorator pattern.
However, overriding all the JComponent methods in the abstract decorator class to call the associated methods in the decorator's concrete JComponent field seems a very monotonous and lengthy task .
JComponent is the superclass
the swing components are what I call"concrete components"
publicclass Decoratorextends JComponent{
JComponent concreteComp;
// JComponent Methods
publicvoid myJComponentMethod(args...){
concreteComp.myJComponentMethod(args.....);
}
// line upon line of boring code...
// end of JComponent methods
}
publicclass ColorChangerextends Decorator.....
Is there a quick way to assign the methods of concreteComp to the methods of Decorator? I thought about using java.lang.reflect to get method pointers for the concreteComp field but I wouldn't know how to assign these to my decorator class anyhow.
Has anyone got any ideas? Thanks,
There are practical limitations to the applicability of the Decorator/Facade patterns. Swing's extensive API makes it a bit difficult, although you could get mileage out of a wrapper base class that delegates *all* its methods to the target. Then your derived class need only override those methods of interest.
One thing to note though, is that Swing components have an awareness of whether they are actually within a component hierarchy or not, so you may get unexpected behavior delegating to a component which has not actually been added to your hierarchy.
I am nto sure it is a decorator pattern...
Decorator pattern is something , like during runtime, you will be creating the objects from another object and thus saving the resource and time by creating the object from instance.
Extending the functionality is not the Decorator pattern.
>Extending mouse adapter is definately the way i'd go if I just wanted to adapt
>one type of swing component. Here however I'd like to do this for several
>components in the api. Buttons and Panels for example.
You're actually adapting one type of component, namely java.awt.Component. This is what supports mouse listeners and changing color.
Btw, a decorator that changes a couple of properties doesn't have to modify (i.e. decorate) the behavior of the target object, but can just do that - change the properties of interest. Only if the properties were not settable (no setFooProperty method) it would be necessary to use the Decorator pattern.
ounosa at 2007-7-13 17:38:44 >
