Home » Software Development » Structural Design Patterns: Composite Pattern

About Emmanouil Gkatziouras

Emmanouil Gkatziouras
He is a versatile software engineer with experience in a wide variety of applications/services.He is enthusiastic about new projects, embracing new technologies, and getting to know people in the field of software.

Structural Design Patterns: Composite Pattern

Previously we checked the adapter pattern the use cases and the bridge pattern. The pattern we will examine in this post is the composite pattern.

By following the composite pattern we “compose” objects into tree structures representing part-whole hierarchies, therefore clients can treat individual objects and compositions uniformly.

By referencing the word hierarchies the first thing that comes to mind is organisations. A military organisation is a great example for the composite pattern.

One of the most basic actions of military personnel is to execute orders.
Thus we will make an interface which specifies the ability to execute orders.

package com.gkatzioura.design.structural.composite;

public interface MilitaryPersonnel {

    void executeOrder();

}

The private is the lowest rank in a military organisation. A private cannot delegate a task or give orders. Therefore he will just execute an order.

package com.gkatzioura.design.structural.composite;

public class Private implements MilitaryPersonnel {

    @Override
    public void executeOrder() {

    }

}

Above the private there are other ranks like Major, Lieutenant, Colonel etc. Those are officer ranks and officers execute orders but also they can assign orders.

So the Officer interface will specify the ability to assign orders.

package com.gkatzioura.design.structural.composite;

public interface Officer {

    void assignOrder();

}

Be aware that an officer in order to execute an order he will take some actions on his own and he might as well assign some orders to lower rank personnel.

So the Lieutenant will be able to execute orders but also to assign orders to ranks lower that him.

package com.gkatzioura.design.structural.composite;

import java.util.ArrayList;
import java.util.List;

public class Lieutenant implements MilitaryPersonnel, Officer {

    private List<MilitaryPersonnel> lowerRankersonel = new ArrayList<>();

    public Lieutenant(List<MilitaryPersonnel> lowerRankersonel) {
        this.lowerRankersonel = lowerRankersonel;
    }

    public void addPrivateUnderCommand(Private soldier) {
        lowerRankersonel.add(soldier);
    }
    
    @Override
    public void executeOrder() {
        
        //other actions

        assignOrder();

        //other actions.
    }

    @Override
    public void assignOrder() {

        lowerRankersonel.forEach(lr->lr.executeOrder());
    }
}

The same that applies to the lieutenant applies to the major who is able to execute orders and assign orders to lower ranks.

package com.gkatzioura.design.structural.composite;

import java.util.ArrayList;
import java.util.List;

public class Colonel implements MilitaryPersonnel, Officer {

    private List<MilitaryPersonnel> lowerRankersonel = new ArrayList<>();

    public Colonel(List<MilitaryPersonnel> lowerRankersonel) {
        this.lowerRankersonel = lowerRankersonel;
    }

    public void addPrivateUnderCommand(Private soldier) {
        lowerRankersonel.add(soldier);
    }

    public void addLieutenantUnderCommand(Lieutenant lieutenant) {
        lowerRankersonel.add(lieutenant);
    }

    @Override
    public void executeOrder() {
        //other actions

        assignOrder();

        //other actions
    }

    @Override
    public void assignOrder() {
        lowerRankersonel.forEach(lr->lr.executeOrder());
    }
}

In our scenario the general is the highest rank and thus when he assigns an order this order will be executed by the composite we implemented.

package com.gkatzioura.design.structural.composite;

import java.util.ArrayList;
import java.util.List;

public class General implements  Officer {

    private List<MilitaryPersonnel> lowerRankersonel = new ArrayList<>();

    public General(List<MilitaryPersonnel> lowerRankersonel) {
        this.lowerRankersonel = lowerRankersonel;
    }

    @Override
    public void assignOrder(MilitaryPersonnel militaryPersonnel) {
        militaryPersonnel.executeOrder();
    }
}

And a main class will display the composite’s functionality.

package com.gkatzioura.design.structural.composite;

import java.util.Collections;

public class CompositeScenario {

    public static void main(String[] args) {

        Private ryan = new Private();
        Lieutenant lieutenant = new Lieutenant(Collections.singletonList(ryan));
        Major major = new Major(Collections.singletonList(lieutenant));
        General general = new General();
        general.assignOrder(major);
    }
}

As you can see the general object, which is the client treated all the objects uniformly.

The whole hierarchy is represented in a tree structure.

The private is the leaf the major and the lieutenant represent the Composite that forwards the requests to the corresponding child components.

You can find the source code on github.

Published on Java Code Geeks with permission by Emmanouil Gkatziouras, partner at our JCG program. See the original article here: Structural Design Patterns: Composite Pattern

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
1 Comment Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Savotije Petrovic Recent comment authors

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

  Subscribe  
newest oldest most voted
Notify of
Savotije Petrovic
Guest
Savotije Petrovic

Pattern contains errors. For example, Officer interface should look like this:

public interface Officer
{
void assignOrder(MilitaryPersonnel militaryPersonnel);
}

Instead of:

public interface Officer
{
void assignOrder();
}

Same goes for classes that implement interface.