I have a Java class (SquareIcon) that implements the Icon interface. It draws a square, of which you can choose the size and color when you create one. I now want to write a class using the Composite Pattern (CompositeIcon), which makes it possible for one to draw several different squares. I’ve read about the Composite Pattern, but I just can’t seem to make it work.
In the SquareIcon class, I have the following three methods:
getIconHeightgetIconWidhtpaintIcon
I have to put all of these in the CompositeIcon class too, right? But how do I do this? I’ve been thinking of something along these lines, but I don’t know if this is right:
public int getIconWidth() {
for (Icon i : icons) {
i.getIconWidth();
}
}
I also have no idea how to do this for the paintIcon method, since it takes 4 parameters, which means this won’t work.
A Composite pattern treats leaf and parent classes the same.
You have to start with a common interface:
Leaf implements the interface:
So does the Parent, which has a collection of Leaf children:
Your code should deal with collections of Icons. You can all the paint() method on leaves and parents.
Any parent in the collection will recursively call its children all the way to leaf nodes in the tree.