Problem

An application needs to manipulate a combination of primitive and complex objects. If the handling differs between those, it would be undesirable to always query the type of object being handled.

Solution

Compose objects into recursive tree structures to represent hierarchies. Define an abstract base class that specifies the behavior to be exercised uniformly across all primitive and composite objects.

Related Patterns

Discussion

Each Composite object only couples itself with the abstract type as it manages its children. Use this pattern whenever you have composites than can contain either components or other composites.

Examples

Arithmetic expressions can be represented as Composites. Each operand is the root of a tree. Child nodes can be other operands or a number, a terminal node. With the abstract class, we can treat this Composite as one expression and let the Composite handle that.

Code

This JavaScript snippet defines a tree structure where a node can have some value as its name and any number of children in an array.

var Node = function(name){
  this.children = [];
  this.name = name;
}
Node.prototype = {
  add:function(child){
    this.children.push(child);
  },
  remove:function(child){
    for(var i = 0; i < this.children.length; i++){
      if(this.children[i] === child){
        this.children.splice(i, 1);
        return;
      }
    }
  },
  getChild:function(i){return this.children[i];}
  hasChildren:function(){return this.children.length > 0}
}

function traverse(indent, node){
  console.log(Array(indent++).join("--") + node.name);
  for(var i = 0; i < node.children.length; i++){
    traverse(indent, node.getChild(i));
  }
}