DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Structural Design Patterns: Composite Pattern

Want to learn more about structural design patterns? Check out this post on using the composite pattern in Java with this tutorial.

Emmanouil Gkatziouras user avatar by
Emmanouil Gkatziouras
CORE ·
Aug. 10, 18 · Tutorial
Like (24)
Save
Tweet
Share
17.06K Views

Join the DZone community and get the full member experience.

Join For Free

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 organizations. A military organization is a great example of the composite pattern.

One of the most basic actions of military personnel is to execute orders. Thus, we will make an interface that 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, they will 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. Officers execute orders, but they can also 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.

Next, the lieutenant will be able to execute orders and assign orders to ranks lower than 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 that 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 is the client treated as all the objects uniformly. The whole hierarchy is represented in a tree structure. The private is the leaf, and the major and the lieutenant represent the composite that forwards the requests to the corresponding child components.

You can find the source code here on GitHub.

Composite pattern Design

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Choosing the Best Cloud Provider for Hosting DevOps Tools
  • Top 5 Java REST API Frameworks
  • Utilize OpenAI API to Extract Information From PDF Files
  • The Top 3 Challenges Facing Engineering Leaders Today—And How to Overcome Them

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: