Composite Pattern

Composite Pattern

In this unit, we will delve into the Composite pattern, a pivotal structural design pattern that facilitates treating individual objects and compositions of objects in a unified manner. This pattern is particularly useful when you need to represent part-whole hierarchies, and you want to be able to interact with those hierarchies in a consistent manner.

What You'll Learn

In this lesson, you will master:

  • The core concept of the Composite pattern.
  • How to implement the Composite pattern using a real-world example involving employees in a company.
  • The significance and benefits of using the Composite pattern in software development.

Let's explore the Composite pattern through a practical example.

Implementing the Composite Pattern

Our example will focus on an organizational structure where we have different types of employees, such as Developers and Managers, and we want to group them within a company directory. This example will help you understand how to manage a collection of objects in a tree structure.

Step 1: Define the Component Interface

First, we define the Employee interface, which declares a method for showing employee details.

public interface Employee {
    void showEmployeeDetails();
}

In this example, Employee is the component interface that declares the showEmployeeDetails method. All concrete employee classes will implement this interface.

Step 2: Implement the Leaf Components

Next, we create the Developer and Manager classes that implement the Employee interface. These classes represent the leaf nodes in the composite structure.

Developer class:

public class Developer implements Employee {
    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() {
        System.out.println(empId + " " + name + " " + position);
    }
}

Manager class:

public class Manager implements Employee {
    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() {
        System.out.println(empId + " " + name + " " + position);
    }
}

The Developer and Manager classes provide the specific details for developers and managers by implementing the showEmployeeDetails method.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal