Composite is a design pattern that lets you compose objects into tree structures later work with these structures as homogeneous objects sharing a common interface.
Let’s say that you have deliverable objects which can be either Products or Boxes, where a Box can contain several Products and a number of Boxes. These contained boxes can also contain some Products or Boxes, and so on.
Suppose you need to compute the weight of such a Product or Box, using the composite pattern allows for adding a weight() method on the common interface of Product and Box. Then you just have to provide the proper implementation of the weight() method:
-
for Product directly return the weight value.
-
for Box simply compute the sum of the weights of the contained Products and Boxes.
Now whatever object is given, a Product or a Box, the weight() method will transparently return the correct weight for the object.
Applying the Composite pattern
-
In the model, select the existing package where you want to create the composite pattern classes.
-
From the contextual menu (rightclick) execute the
Java Architect →
Patterns → Create composite command.
-
The command will pop the following GUI

-
Fill the fields in the form (the drawn figure in the dialog shows the role of each value):
-
Composite: the name of the 'common interface', Deliverable in our example
-
Composed: the name of the 'container' element, Box in our example
-
Leaf name: the name of the 'simple' element, Product in our example
-
Relationship name: the name of the composition between Composed and Composite
-
-
Press the OK button to apply the pattern and create the Composite class model under the selected package.