Composite Design Pattern Cont..

public class LeafNode implements Node {
      private String nodeData;

       public LeafNode(String nodeData) {
                 this.nodeData = nodeData;

       public void printNodeData() {
                System.out.println("Leaf data: " + nodeData);

       public Node getChild(int index) {
                return null;

       public int getChildCount() {
                return 0;

       public String toString() {
               return nodeData;

How to use these classes and interface: We can build the company hierarchy using the classes and we can display the hierarchy using the node interface. To do this we can write a test class to create and display the company hierarchy.

public class CompositePatternTest {

    public static void main(String[] args) {
        Node node = getCompanyStructure();
    private static void printDetails(Node parent) {
        if (parent.getChildCount() == 0) {
            for (int i = 0; i < parent.getChildCount(); i++) {
                Node child = parent.getChild(i);
                System.out.println(child +" Reporting to "+parent);

    private static Node getCompanyStructure() {
        //Create manager as Composite node as it has to hold employees as child nodes
        CompositeNode managerNode1 = new CompositeNode("Manager1");
        //Create employees as leaf nodes, as these will not have any child
        LeafNode employee1 = new LeafNode("Employee1");
        LeafNode employee2 = new LeafNode("Employee2");

        CompositeNode managerNode2 = new CompositeNode("Manager2");
        employee1 = new LeafNode("Employee1");
        //Create CEO as Composite node as it has to hold managers as child nodes
        CompositeNode companyCEO = new CompositeNode("Company CEO");
        //Create Company as Composite node as it has to hold CEO as child node
        CompositeNode company = new CompositeNode("Company");

        return company;  //returns the company structure in single object


Company CEO Reporting to Company 
Manager1 Reporting to Company CEO 
Employee1 Reporting to Manager1 
Employee2 Reporting to Manager1 
Manager2 Reporting to Company CEO
Employee1 Reporting to Manager2

As we can see it is very simple to represent the complex tree structure using composite pattern.
Composite pattern can be used in following many situations few of them are given here.

  • Representing parent child relation ship for a family.
  • Representing a tree hierarchy for example Folder and Files.
  • Representing a xml elements hierarchy.
  • Representing GUI components hierarchy as in java swing JComponent etc.