MBrown
MBrown

Reputation: 593

How to do a class with the composite pattern?

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:

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.

Upvotes: 1

Views: 566

Answers (1)

duffymo
duffymo

Reputation: 308733

A Composite pattern treats leaf and parent classes the same.

You have to start with a common interface:

public interface Icon {
    void paint();
}

Leaf implements the interface:

public class LeafIcon implements Icon {
    public void paint() { 
        // more here
    }
}

So does the Parent, which has a collection of Leaf children:

public class ParentIcon implements Icon {
    private List<Icon> children = new ArrayList<Icon>();
    public void paint() {
        for (Icon child : children) {
            child.paint();
        }
    }
}

Your code should deal with collections of Icons. You can all the paint() method on leaves and parents.

List<Icon> icons = new ArrayList<Icon>();
for (Icon icon : icons) {
    icon.paint();
}

Any parent in the collection will recursively call its children all the way to leaf nodes in the tree.

Upvotes: 4

Related Questions