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

  1. In the model, select the existing package where you want to create the composite pattern classes.

  2. From the contextual menu (rightclick) execute the module Java Architect → image Patterns → Create composite command.

  3. The command will pop the following GUI

Composite Pattern Dialog - Create
  1. Fill the fields in the form (the drawn figure in the dialog shows the role of each value):

    1. Composite: the name of the 'common interface', Deliverable in our example

    2. Composed: the name of the 'container' element, Box in our example

    3. Leaf name: the name of the 'simple' element, Product in our example

    4. Relationship name: the name of the composition between Composed and Composite

  2. Press the OK button to apply the pattern and create the Composite class model under the selected package.