The Composite Pattern

Problem

Trees are commonly used to represent assemblies and other types of hierarchies.

Solution

The Composite Pattern introduces an abstract Component interface. There are two types of components: primitive or simple components and composite components (also called assemblies or aggregates). A composite component maintains a list of references (or copies) of its parts or children. These parts may be primitives or composites.

Structure

Behavior

Discussion

The following Java implementation introduces Component as an empty interface:

interface Component { }

Alternatively, the Component base class could maintain a reference to its parent:

class Component {
   protected Composite parent = null;
   // etc.
}

Primitive components are generics that can contain any type of data:

class Primitive<Data> implements Component {
   private Data data;
   public Primitive(Data data) {
      this.data = data;
   }
   public Data getData() { return data; }
   public void setData(Data data) { this.data = data; }
}

A composite maintains a set of children which may be primitives or composites:

public class Composite implements Component {
   private Set<Component> children = new HashSet<Component>();
   public void add(Component child) { children.add(child); }
   public void remove(Component child) { children.remove(child); }
   public Iterator iterator() { return children.iterator(); }
};

Here's some sample client Code:

      Primitive<String> leaf1 = new Primitive<String>("Leaf 1");
      Primitive<String> leaf2 = new Primitive<String>("Leaf 2");
      Primitive<String> leaf3 = new Primitive<String>("Leaf 3");
      Composite parent1 = new Composite();
      Composite parent2 = new Composite();
      parent1.add(leaf1);
      parent1.add(leaf2);
      parent2.add(parent1);
      parent2.add(leaf3);

Here is a drawing of the tree the client constructed: