#
Composite
This tutorial explains to you the design pattern named Composite (which is a Structural Pattern).
#
Composite Pattern - theory
Composite
design pattern in Java allows you to have a tree structure and ask each node in the tree structure to
perform a task. This pattern produce a hierarchical tree which can be accessed by using a uniform method.
Take a look at the following UML diagram representing the Composite design pattern:
#
Composite Pattern - example
Here is that example using the Composite Design Pattern in Java:
package composite.java.example;
import java.util.ArrayList;
import java.util.List;
public class Employee {
private String name;
private String job;
private List<Employee> subordinates;
public Employee(String name, String job) {
this.name = name;
this.job = job;
subordinates = new ArrayList<Employee>();
}
public void add(Employee e) {
subordinates.add(e);
}
public void remove(Employee e) {
subordinates.remove(e);
}
public List<Employee> getSubordinates(){
return subordinates;
}
public String toString(){
return ("( Name : " + name + ", Job : " + job +" )");
}
}
package composite.java.example;
public class JavaCompositePatternExample {
public static void main(String[] args) {
Employee pres = new Employee("Greg","President");
Employee vp1 = new Employee("Dana","Vice-President");
Employee dir1 = new Employee("Mark","Director");
Employee dir2 = new Employee("Emanuil","Director");
Employee mark1 = new Employee("Laura","Marketing");
pres.add(vp1);
vp1.add(dir1);
vp1.add(dir2);
dir1.add(mark1);
for (Employee emp1 : pres.getSubordinates()) {
System.out.println("Level1: "+emp1);
for (Employee emp2 : emp1.getSubordinates()) {
System.out.println("Level2: "+emp2);
}
}
}
}
When you run this example you will receive the following result: