Composite Design Pattern

Composite Design Pattern

The Composite Design Pattern is a structural design pattern that enables the composition of objects into tree structures to represent part-whole hierarchies. This pattern allows clients to treat individual objects and object compositions uniformly.

Let us look at a problem that we come across through an illustration image

Composite Design Pattern Problem

The illustration shows the organizational structure of a company in a simplified manner while drawing attention to an issue that the Composite design Pattern can effectively resolve. The organization is organized into departments within this structure, and teams within each department are composed of workers.

This configuration shows how difficult it can be to aggregate and manage data across hierarchies, for example, to determine the total number of hours worked by an employee. Such a hierarchical structure can be difficult to manage without the Composite design Pattern, particularly when it comes to tasks that must be completed consistently at all levels (departments, teams, and employees).

But what is the solution? Are you curious to know the solution? Let’s dive in!

Using the Composite Design Pattern for the organizational structure problem, you would interact with both Departments and Employees through a common interface that declares a method for calculating the total working hours.

How does this method function?

  • For an individual employee, it would simply return the employee’s hours.
  • For a department, it would iterate over each member the department contains, accumulate their hours, and return the total for that department.
  • If a member happens to be a sub-department, this sub-department would in turn aggregate the hours of its members, and this process would continue recursively until the hours of all members are accounted for.
  • A department could also account for additional factors, such as overtime hours.

Real-world Example

An academic university’s structure serves as a real-world analogy for the Composite Design Pattern.

The University itself is at the top of the hierarchy. The University is organized into a number of composite Schools or Faculties, such as the School of Engineering, School of Medicine, and School of Humanities. These schools have departments, such as the mechanical engineering and computer science departments, which are composites that can hold more individuals or structures. A department is made up of programs (such as the Master’s Program in Robotics or the Undergraduate Program in Computer Science), and each program is composed of courses. A professor or lecturer (the leaves in the structure) teaches each course.

Composite design Pattern Read world

All schools are subject to university-level policies and decisions, which are then implemented by the schools according to the needs of their departments, programs, and even the way that courses are taught.

The core of the Composite Design Pattern is demonstrated by this academic structure, which allows the university to uniformly manage operations at any level, from broad strategic planning to the intricacies of individual course offerings.

Structure of Composite Design Pattern

The composite design pattern has some of the key components:

  • Component: This is an abstract class or interface that specifies the shared functions for leaf and composite nodes. It outlines guidelines for managing children and might even set the default behavior for them.
  • Leaf: These are the fundamental components that make up the structure. Things made of leaves don’t have children. They carry out the component’s primitive behavior.
  • Composite: A composite object has other composite objects and leaf elements. It implements methods to add, remove, or access child components that are specified in the component interface.
  • Client: Using the component interface, the client can modify objects within the composition.
Implementation of Composite Design Pattern

Let’s implement the organization example in multiple languages.

Pseudocode

Here’s the pseudocode for the Composite Design Pattern applied to the employee problem:

INTERFACE OrganizationComponent
    METHOD getName()
    METHOD getHours()

CLASS Employee IMPLEMENTS OrganizationComponent
    PRIVATE name, hours
    CONSTRUCTOR(name, hours)
        this.name = name
        this.hours = hours
    METHOD getName()
        RETURN name
    METHOD getHours()
        RETURN hours

CLASS Department IMPLEMENTS OrganizationComponent
    PRIVATE name, components = new List<OrganizationComponent>
    CONSTRUCTOR(name)
        this.name = name
    METHOD getName()
        RETURN name
    METHOD getHours()
        totalHours = 0
        FOR component IN components
            totalHours += component.getHours()
        RETURN totalHours
    METHOD addComponent(component)
        components.add(component)

In this pseudocode, the OrganizationComponent serves as the common interface for both Employee (leaf) and Department (composite), allowing clients to interact with them uniformly. A Department can have other Department(s) or Employee(s) as children and calculate total hours by aggregating the hours of its components.

Here’s how you can implement the organizational structure example using the Composite Pattern across different languages:

Implementation

package com.ashok.designpatterns.composite;

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

/**
 * 
 * @author ashok.mariyala
 *
 */
interface OrganizationComponent {
    String getName();
    int getHours();
}
package com.ashok.designpatterns.composite;
/**
 * 
 * @author ashok.mariyala
 *
 */
class Employee implements OrganizationComponent {
    private String name;
    private int hours;

    public Employee(String name, int hours) {
        this.name = name;
        this.hours = hours;
    }

    public String getName() {
        return name;
    }

    public int getHours() {
        return hours;
    }
}
package com.ashok.designpatterns.composite;
/**
 * 
 * @author ashok.mariyala
 *
 */
class Department implements OrganizationComponent {
    private String name;
    private List<OrganizationComponent> components = new ArrayList<>();

    public Department(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public int getHours() {
        int totalHours = 0;
        for (OrganizationComponent component : components) {
            totalHours += component.getHours();
        }
        return totalHours;
    }

    public void addComponent(OrganizationComponent component) {
        components.add(component);
    }
}
package com.ashok.designpatterns.composite;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class Solution {
    public static void main(String[] args) {
        Department developmentDepartment = new Department("Development");
        Department marketingDepartment = new Department("Marketing");

        Employee ashok = new Employee("Ashok Kumar", 40);
        Employee dillesh = new Employee("Dillesh", 45);
        Employee thiru = new Employee("Thiru", 50);

        developmentDepartment.addComponent(ashok);
        developmentDepartment.addComponent(dillesh);
        marketingDepartment.addComponent(thiru);

        System.out.println("Total Hours in Development Department: " + developmentDepartment.getHours());
        System.out.println("Total Hours in Marketing Department: " + marketingDepartment.getHours());
    }
}
Application of Composite Pattern

The Composite Design Pattern is useful in many situations where you have a part-whole hierarchy and you want to handle individual objects and their compositions consistently. Typical uses for these include:

  • Graphical User Interface (GUIs) Some of the GUIs have complex layouts. Composite design patterns can handle such GUIs very efficiently. Panels, frames, and buttons are examples of components that can be nested in different ways. This pattern enables the same treatment of individual parts and compositions (such as a panel with buttons).
  • File Directories Directories in file systems can contain files and other directories. The Composite Design Pattern enables operations such as searching, copying, and size calculation to be performed uniformly on both files (leaf nodes) and directories (composite nodes).
  • Organizational Structure This pattern can be used to manage organizational charts that include departments, teams, and individual employees, as demonstrated in the example. This enables the execution of tasks such as computing total work hours or uniformly allocating resources throughout the hierarchy.
  • Menus Another appropriate use case is application menus, particularly those with nested submenus. Whether it’s a last action item or a container for additional items, every menu item (which may also be a submenu) is handled consistently.
  • Document Object Model (DOM) of web pages The DOM is a tree structure of elements used in web development. The Composite Pattern can be used to apply styling, scripting, and other effects consistently to individual elements and nested structures (such as a div that contains paragraphs and other divs).

The Composite Design Pattern is particularly useful in scenarios where you have a part-whole hierarchy and want to treat individual objects and compositions uniformly. This pattern simplifies the client code and enhances the flexibility and extensibility of the design.

That’s all about the Composite Design Pattern. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Design patterns.!!

Composite Design Pattern
Scroll to top