Skip to content

OOP: Composite Pattern

Mani Bhushan edited this page Sep 10, 2016 · 3 revisions

Design Patterns - Composite Pattern

Composite pattern is used where we need to treat a group of objects in similar
way as a single object. Composite pattern composes objects in term of a tree structure
to represent part as well as whole hierarchy. This type of design pattern comes
under structural pattern as this pattern creates a tree structure of group of objects.

Key Idea.
This pattern creates a class that contains group of its own objects. This class provides     
ways to modify its group of same objects.
Example:
public class Employee {

	private String name;
	private String department;
	private double salary;
	private List<Employee> subordinates;
        
        public Employee(String name, String department, double salary) {
		this.name = name;
		this.department = department;
		this.salary = salary;
		this.subordinates = new ArrayList<Employee>();
	}
}
DFS print of employee hierarchy.
	public void showEmployees() {
		Employee emp = this;
		showEmployees(emp);
		
	}
	
	private void showEmployees(Employee emp) {
		if (emp == null) {
			return;
		}
		System.out.print(emp + "\t");
		
		int size = emp.subordinates.size();
		for (int i=0; i<size; i++) {
			Employee e = emp.subordinates.get(i);
			showEmployees(e);
		}
		System.out.println();
	}
BFS print of employee hierarchy.
	public void printEmployeeHeirarchy() {
		Employee employee = this;
		
		Queue<Employee> queue = new LinkedList<Employee>();
		queue.add(employee);
		
		Employee marker = new Employee();
		queue.add(marker);
		
		while (!queue.isEmpty()) {
			Employee e = queue.remove();
			if (e.equals(marker)) {
				System.out.println();
				if (!queue.isEmpty()) {
					queue.add(marker);
				}
			} else {
				System.out.print(e + "\t");
				int size = e.subordinates.size();
				for (int i=0; i<size; i++) {
					queue.add(e.subordinates.get(i));
				}
			}
		}
	}

Clone this wiki locally