# Composite Pattern

version 3.0.3

The Composite Pattern allows you to treat single instances of an object the same way as a group of objects. The pattern is often used with hierarchies of objects. Typically, one or more methods should be callable in the same way for either leaf or composite nodes within the hierarchy. In such a case, composite nodes typically invoke the same named method for each of their children nodes.

## 1. Example

Consider this usage of the composite pattern where we want to call `toString()` on either `Leaf` or `Composite` objects.

In Java, the `Component` class is essential as it provides the type used for both leaf and composite nodes. In Groovy, because of duck-typing, we don’t need it for that purpose, however, it can still serve as a useful place to place common behaviour between the leaf and composite nodes.

For our purposes, we will assemble the following hierarchy of components.

Here is the code:

    abstract class Component {
        def name
        def toString(indent) {
            ("-" * indent) + name
        }
    }

    class Composite extends Component {
        private children = []
        def toString(indent) {
            def s = super.toString(indent)
            children.each { child ->
                s += "\\n" + child.toString(indent + 1)
            }
            s
        }
        def leftShift(component) {
            children << component
        }
    }

    class Leaf extends Component { }

    def root = new Composite(name: "root")
    root << new Leaf(name: "leaf A")
    def comp = new Composite(name: "comp B")
    root << comp
    root << new Leaf(name: "leaf C")
    comp << new Leaf(name: "leaf B1")
    comp << new Leaf(name: "leaf B2")
    println root.toString(0)

Here is the resulting output:

    root
    -leaf A
    -comp B
    --leaf B1
    --leaf B2
    -leaf C