Composite – A Structural Design Pattern

Composite Design Pattern – Initial Concept

This springcavaj – Structural Design Pattern page briefly describes the Initial Concept of Structural Design Patterns, advantages, disadvantages, benefits, various types, common problems, and a few interview questions discussed.

This guide provides a comprehensive understanding of Structural Design Patterns for designing and architecting an application.

What is a Composite Design Pattern

The Composite Pattern is a structural design pattern that allows you to treat individual objects and compositions of objects uniformly. It’s useful when you have to manipulate a tree-like structure.

A component can be either a leaf (individual object) or a composite (collection of components).

The client treats both leaf and composite uniformly using the component interface.

What are the features of the Composite Design Pattern?

  • Tree Structure – Some examples are like files/folders, menus/submenus.
  • Component Interface – It defines the common behavior.
  • Recursive Composition – A Composite can contain other composites or leaves.

What are the advantages of the Composite Design Pattern?

  • Uniformity – Treats individual and group objects in the same way.
  • Flexibility – Adds new elements without affecting client code.
  • Simplified Client Code – No need to distinguish between leaf and composite.
  • Scalable – Easily expands the structure as needed.

What are the disadvantages of the Composite Design Pattern?

  • Can be Overkill – For flat structures, the pattern adds unnecessary complexity.
  • Hard to restrict – It’s difficult to prevent certain operations in composites or leaves.
  • Runtime Type Checks – Sometimes needs casting or type checks to access specific functionality.

What are the use cases of the Composite Design Pattern?

  • File systems (folders, files)
  • Organization hierarchies
  • GUI components (menus, toolbars)
  • Graphic rendering systems (shapes made of smaller shapes)

Brief Description of Implementation

I have developed a small program to help you understand the working principle of the Bridge Design Pattern. The code is uploaded to GitHub as the springcavaj-designpattern repository. Please clone the application and import it into any of the supported IDs, such as STS or Eclipse.

After successfully importing the above code base, one will find a class named CompositeMasterclassApplication.java in the com.springcavaj.designpattern.composite package. Please see the screenshot attached below.

Here you can see the class under the com.springcavaj.designpattern.composite package is CompositeMasterclassApplication.java. Right-click on the class, select the Run As option, and then Java Application. It will run and generate the output as provided below.

INFO com.springcavaj.designpattern.composite.CompositeMasterclassApplication - Composite Design Pattern Example

INFO com.springcavaj.designpattern.composite.design.impl.CompanyCompositeDirectory - List of Employees are : [Developer [name=John, empId=100, position=Developer]]

INFO com.springcavaj.designpattern.composite.design.impl.CompanyCompositeDirectory - List of Employees are : [Developer [name=John, empId=100, position=Developer], Developer [name=David, empId=101, position=Senior Developer]]

INFO com.springcavaj.designpattern.composite.design.impl.CompanyCompositeDirectory - List of Employees are : [com.springcavaj.designpattern.composite.design.impl.CompanyCompositeDirectory@7aec35a]

INFO com.springcavaj.designpattern.composite.design.impl.CompanyCompositeDirectory - List of Employees are : [com.springcavaj.designpattern.composite.design.impl.CompanyCompositeDirectory@7aec35a, Manager [name=Sophie, empId=200, position=Manager]]

INFO com.springcavaj.designpattern.composite.design.impl.Developer - Employee ID : 100, Name : John, Position : Developer

INFO com.springcavaj.designpattern.composite.design.impl.Developer - Employee ID : 101, Name : David, Position : Senior Developer

INFO com.springcavaj.designpattern.composite.design.impl.Manager - Employee ID : 200, Name : Sophie, Position : Manager

INFO com.springcavaj.designpattern.composite.design.impl.CompanyCompositeDirectory - List of Employees are : [com.springcavaj.designpattern.composite.design.impl.CompanyCompositeDirectory@7aec35a]

INFO com.springcavaj.designpattern.composite.design.impl.Developer - Employee ID : 100, Name : John, Position : Developer

INFO com.springcavaj.designpattern.composite.design.impl.Developer - Employee ID : 101, Name : David, Position : Senior Developer

Detailed Explanation

The code provided below models an employee hierarchy (similar to an organizational structure) where both individual employees (developers, managers) and groups of employees (departments/teams) can be treated uniformly using a common interface.

Employee.java

It is the component interface that declares a common method named showEmployeeDetails(). Both leaf and composite classes implement this interface.

public interface Employee {
	void showEmployeeDetails();
}

Developer.java & Manager.java

Both classes are leaf class that implements the Employee interface and overrides the showEmployeeDetails() method.

public class Developer implements Employee {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(Developer.class);
	
	private String name;
    private long empId;
    private String position;
    
    public Developer(long empId, String name, String position) {
        this.empId = empId;
        this.name = name;
        this.position = position;
    }

	@Override
	public void showEmployeeDetails() {
		LOGGER.info("Employee ID : {}, Name : {}, Position : {}", this.empId, this.name, this.position);
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Developer [name=");
		builder.append(name);
		builder.append(", empId=");
		builder.append(empId);
		builder.append(", position=");
		builder.append(position);
		builder.append("]");
		return builder.toString();
	}
}
public class Manager implements Employee {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(Manager.class);
	
	private String name;
    private long empId;
    private String position;

    public Manager(long empId, String name, String position) {
        this.empId = empId;
        this.name = name;
        this.position = position;
    }

	@Override
	public void showEmployeeDetails() {
		LOGGER.info("Employee ID : {}, Name : {}, Position : {}", this.empId, this.name, this.position);
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Manager [name=");
		builder.append(name);
		builder.append(", empId=");
		builder.append(empId);
		builder.append(", position=");
		builder.append(position);
		builder.append("]");
		return builder.toString();
	}
}

CompanyCompositeDirectory.java

Contains a list of Employee objects. Can contain both leaves (Developer, Manager) and other composites (CompanyCompositeDirectory). Implements showEmployeeDetails() method by recursively calling it on all its children.

public class CompanyCompositeDirectory implements Employee {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CompanyCompositeDirectory.class);
	
	private List<Employee> employees = new ArrayList<>();
	
	public void addEmployee(Employee employee) {
		employees.add(employee);
		LOGGER.info("List of Employees are : {}", employees);
	}
	
	public void removeEmployee(Employee employee) {
		employees.remove(employee);
		LOGGER.info("List of Employees are : {}", employees);
	}

	@Override
	public void showEmployeeDetails() {
		for(Employee employee : employees) {
			employee.showEmployeeDetails();
		}
	}

}

Lastly, the class named CompositeMasterclassApplication.java is there to run the application and see how the Company’s Employee Hierarchy is created.

Steps to run the application

The complete Run application steps are provided in this README.md file, but still, I am still providing the steps to run points below.

  • Clone the sprincavaj-designpattern application from the GitHub repository.
  • Import the application as a Maven application, either in STS or Eclipse.
  • Find the CompositeMasterclassApplication.java class.
  • Right-click on the file and select Run As -> Java Application.

GitHub Code Link

Download the Source Code from GitHub

Common Problems Faced in Implementing the Composite Pattern

Composite Design Pattern Common Problems

Interview FAQs

Composite Design Pattern Interview FAQs

Other Useful Links

Implementations of various components of Spring Boot

Other Design Pattern Links

Creational Design Patterns

Factory Design Pattern

Abstract Factory Design Pattern

Builder Design Pattern

Prototype Design Pattern

Singleton Design Pattern

Structural Design Patterns

Adapter Design Pattern

Bridge Design Pattern

Decorator Design Pattern