Skip to content

Demystifying the Composite Design Pattern in Java

Posted on:September 10, 2022 at 01:13 PM

The Composite design pattern is a structural design pattern used in software engineering to manage hierarchical data structures. It’s particularly useful when dealing with tree-like structures within an application. In this blog post, we’ll explore the Composite pattern through a simple example and delve into its key concepts.

Table of contents

Open Table of contents

Sections

Applying Operations in the Tree Structure

The Composite pattern allows us to treat individual objects and compositions of objects uniformly. This is achieved by representing the objects in a tree structure. The main idea behind this pattern is to compose objects into a tree to represent part-whole hierarchies.

Let’s illustrate this with a high-level example of a computer system. A computer is composed of various parts such as memory, hard drive, and a processor. Each part can further have subparts. For instance, memory can consist of random access memory (RAM) and read-only memory (ROM). We can visualize this as a tree-like structure where each part is a node, and the subparts are its children.

Understanding the Code

To demonstrate the Composite pattern, let’s consider a simple Java implementation. We have two main classes: Equipment and Composite. Equipment represents an individual node in our tree, while Composite represents a composite node that can contain other nodes.

In this example, each equipment has a name and a price. A composite can contain multiple equipments. We can calculate the total price of a composite by summing up the prices of its components.

Equipment Classs

class Equipment {
    private String name;
    private int price;

    public Equipment(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public int getPrice() {
        return price;
    }
}

Composite Classs

class Composite extends Equipment {
    private ArrayList<Equipment> equipments;

    public Composite(String name) {
        super(name, 0);
        this.equipments = new ArrayList<>();
    }

    public void addEquipment(Equipment equipment) {
        equipments.add(equipment);
    }

    @Override
    public int getPrice() {
        int sum = 0;
        for (Equipment equipment : equipments) {
            sum += equipment.getPrice();
        }
        return sum;
    }
}

Example Usage

We demonstrate the usage of the Composite pattern by constructing a computer with various components such as a processor, hard drive, and memory. The memory itself is a composite containing RAM and ROM. We calculate the total price of the computer by invoking the getPrice() method on the root composite.

public class Client {
    public static void main(String[] args) {
        Composite computer = new Composite("PC");

        Equipment processor = new Equipment("Processor", 1000);
        Equipment hd = new Equipment("Hard Drive", 250);

        Composite memory = new Composite("Memory");
        Equipment rom = new Equipment("Read Only Memory", 75);
        Equipment ram = new Equipment("Random Access Memory", 100);

        memory.addEquipment(rom);
        memory.addEquipment(ram);

        computer.addEquipment(processor);
        computer.addEquipment(hd);
        computer.addEquipment(memory);

        int totalPrice = computer.getPrice();
        System.out.println("Total Price of the computer: $" + totalPrice);
    }
}

Conclusion

The Composite design pattern is a powerful tool when dealing with hierarchical structures. By treating individual objects and compositions uniformly, we can perform operations seamlessly throughout the tree structure. Understanding and implementing the Composite pattern can significantly enhance the scalability and flexibility of applications dealing with complex object hierarchies.

That concludes our exploration of the composite Design Pattern. Stay tuned for more insights into design patterns and software development concepts.

Happy coding!