Composite Design Pattern

The Composite Design pattern is a structural pattern that defines a way to access a group of objects through a single object. It can be though of as a tree structure where a node holds reference to its children. The main actors in these pattern are

  • Node

    The Node defines an interface that each object in the hierarchy implements. The node can be a composite (contains other nodes) or leaf (does not contain other nodes)

  • Composite Node

    A composite node maintains a reference to a list of child nodes. The composite node could itself be a child node(contains a parent) or can be a root node(does not have a parent)

  • Leaf Node

    A Leaf node cannot contain any children. It can be a specialized node such that it stores only specific values (e.g. TextNode to store only text)

Example
To Demonstrate the composite pattern we develop an interface that can act as both a parent as well as leaf node.

The Node interfaces defines the method to help the Ojbect act as a leaf as well as a parent.

The Implementation class for the Node inteface

The TextNode is a specialized node such that it can store only String values and cannot act as a parent.

The Client demonstrates the creation of a tree structure using the Node interface.

This is the class diagram of the Composite pattern

Composite Design Pattern

Composite pattern is used widely in JSON and XML processing. The composite pattern is ideal in representing a hierarchical document model.

In our example we have a special implementation for the leaf node. However, the leaf node can be another composite node and a specialization is not always required.

The main advantage of composite pattern is that the client can treat the whole hierarchy as a single object and traverse through the tree using the same definition for each node.

What are some of the important considerations

  • In our example we treated the leaf node separately, we can instead treat the composite node separately. The advantage then is that we dont have to maintain the list of Children in the leaf nodes.
  • Deleting a child can be tricky especially if it is not a leaf node.
  • This pattern generally does not have a child that refers to mulitple parents.

This finishes our tutorial on the composite pattern. Its a useful pattern if you have a whole part relationship or a tree kind of structure.

One thought on “Composite Design Pattern

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top
Bitnami