Composite Pattern
# Composite Pattern
The Composite Pattern, also known as the Part-Whole pattern, is used to treat a group of similar objects as a single object. The Composite Pattern composes objects in a tree structure to represent both part and whole hierarchies. This type of design pattern is a structural pattern that creates a tree structure of object groups.
This pattern creates a class that contains its own group of objects. This class provides ways to modify the same group of objects.
We demonstrate the usage of the Composite Pattern through the following example. The example demonstrates the hierarchy of employees in an organization.
## Introduction
### Intent
Compose objects into tree structures to represent part-whole hierarchies. The Composite Pattern allows clients to treat individual objects and compositions of objects uniformly.
### Main Problems Solved
* Simplifies the handling of objects in a tree structure, whether they are individual objects or composite objects.
* Decouples client code from the internal structure of complex elements, allowing clients to handle all types of nodes uniformly.
### Use Cases
* When you need to represent the hierarchy of objects, such as a file system or an organizational structure.
* When you want client code to be able to handle all objects in a tree structure in a consistent manner.
### Implementation Approach
* **Unified Interface**: Define an interface that all objects (both branches and leaves) implement.
* **Composite Structure**: The branch object contains a list of references to the interface, which can be leaves or branches.
### Key Code
* **Component Interface**: Defines the operations that all objects must implement.
* **Leaf Class**: Implements the Component interface, representing a leaf node in the tree.
* **Composite Class**: Also implements the Component interface and contains a collection of other Component objects.
### Application Examples
1. **Arithmetic Expressions**: Construct a tree structure composed of operands, operators, and sub-expressions.
2. **GUI Components**: In Java's AWT and Swing libraries, containers (like Panel) can contain other components (like buttons and checkboxes).
### Advantages
1. **Simplifies Client Code**: Clients can handle all types of nodes uniformly.
2. **Easy to Extend**: New leaf types or branch types can be added easily.
### Disadvantages
* **Violates the Dependency Inversion Principle**: The declaration of components is based on concrete classes rather than interfaces, which may reduce code flexibility.
### Usage Recommendations
* During design, prioritize using interfaces over concrete classes to improve system flexibility and maintainability.
* Suitable for scenarios that require handling complex tree structures, such as file systems, organizational structures, etc.
### Notes
* During implementation, ensure all components follow a unified interface to maintain consistency.
* Consider using the Factory Pattern to create different types of components to further decouple the creation logic of components.
### Structure
**The core roles of the Composite Pattern include:**
* **Component:**
* Defines a common interface for all objects in the composition. It can be an abstract class or an interface. It declares methods for accessing and managing child components, including adding, removing, and retrieving child components.
* **Leaf:**
* Represents a leaf object in the composition. A leaf node has no children. It implements the methods of the component interface but typically does not contain child components.
* **Composite:**
* Represents a composite object in the composition. A composite node can contain child nodes, which can be leaf nodes or other composite nodes. It implements the methods of the component interface, including methods for managing child components.
* **Client:**
* Interacts with the composite structure through the component interface. The client does not need to distinguish between leaf nodes and composite nodes and can treat the whole and parts uniformly.
## Implementation
We have a class _Employee_, which is used as the composite model class. The _CompositePatternDemo_ class uses the _Employee_ class to add the department hierarchy and print all employees.

### Step 1
Create the _Employee_ class, which has a list of _Employee_ objects.
## Employee.java
import java.util.ArrayList; import java.util.List; public class Employee{private String name; private String dept; private int salary; private Listsubordinates; //Constructor public Employee(String name,String dept, int sal){this.name = name; this.dept = dept; this.salary = sal; subordinates = new ArrayList(); }public void add(Employee e){subordinates.add(e); }public void remove(Employee e){subordinates.remove(e); }public ListgetSubordinates(){return subordinates; }public String toString(){return("Employee :[ Name : "+ name +", dept : "+ dept + ", salary :" + salary+" ]"); }}
### Step 2
Use the _Employee_ class to create and print the employee hierarchy.
## CompositePatternDemo.java
public class CompositePatternDemo{public static void main(String[]args){Employee CEO = new Employee("John","CEO", 30000); Employee headSales = new Employee("Robert","Head Sales", 20000); Employee headMarketing = new Employee("Michel","Head Marketing", 20000); Employee clerk1 = new Employee("Laura","Marketing", 10000); Employee clerk2 = new Employee("Bob","Marketing", 10000); Employee salesExecutive1 = new Employee("Richard","Sales", 10000); Employee salesExecutive2 = new Employee("Rob","Sales", 10000); CEO.add(headSales); CEO.add(headMarketing); headSales.add(salesExecutive1); headSales.add(salesExecutive2); headMarketing.add(clerk1); headMarketing.add(clerk2); //Print all employees of the organization System.out.println(CEO); for(Employee headEmployee : CEO.getSubordinates()){System.out.println(headEmployee); for(Employee employee : headEmployee.getSubordinates()){System.out.println(employee); }}}}
### Step 3
Execute the program, and the output is:
Employee :[ Name : John, dept : CEO, salary :30000 ]Employee :[ Name : Robert, dept : Head Sales, salary :20000 ]Employee :[ Name : Richard, dept : Sales, salary :10000 ]Employee :[ Name : Rob, dept : Sales, salary :10000 ]Employee :[ Name : Michel, dept : Head Marketing, salary :20000 ]Employee :[ Name : Laura, dept : Marketing, salary :10000 ]Employee :[ Name : Bob, dept : Marketing, salary :10000 ]
YouTip