What is the Composite Design Pattern?

We often have to deal with tree structures. There is a great pattern that will help us work with such data and organize code

Jakub Kapuscik
The Startup

--

We often have to deal with nested structures. In a company each department can consists of multiple smaller departments and even they can have more others inside. Such structures often have to be modeled in our applications. Composite shows how we can achieve it and how we can deal with such data.

Real-life examples of tree-structured data could be:

  • HTML DOM
  • company structure. Each person can have a number of subordinates that can have their own subordinates
  • decision trees. Each decision can take us to result or the next decision to make
  • XML structures
  • chapters in a book. Each chapter main consist of a number of sub-chapters

Let’s imagine we are working on a system that will report usage of salary budget in departments of a company. Each department can have sub-departments or a list of employed people with information about their salaries. In this case, a department is a composite structure and the employee is a leaf. A leaf is a structure with no more nested elements. Let’s start with defining a…

--

--