Thursday, April 29, 2010

Composite Pattern

Structural Patterns - Composite Pattern
In developing applications, we come across components which are individual objects and also can be collection of objects. Composite pattern can represent both the conditions. In this pattern, you can develop tree structures for representing part-whole hierarchies.
The most common example in this pattern is of a company’s employee hierarchy. We here will also take the same example.
The employees of a company are at various positions. Now, say in a hierarchy, the manager has subordinates; also the Project Leader has subordinates, i.e. employees reporting to him/her. The developer has no subordinates.
So, let’s have a look at the class Employee: This is a simple class with getters and setters for attributes as name, salary and subordinates.

Employee.java

package structural.composite;

import java.util.Vector;

public class Employee {
private String name;
private double salary;
private Vector subordinates;

public Vector getSubordinates() {
return subordinates;
}
public void setSubordinates(Vector subordinates) {
this.subordinates = subordinates;
}


// constructor
public Employee(String name, double sal) {
setName(name);
setSalary(sal);
subordinates = new Vector();
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}

public void add(Employee e) {
subordinates.addElement(e);
}

public void remove(Employee e) {
subordinates.remove(e);
}
}// End of interface
Next we, fill up the tree. You can make a class to access the class Employee and try filling up the tree like this:


/**
* This will add employess to the tree. The boss, is PM
* and has subordinates.
*/
private void addEmployeesToTree() { CFO = new Employee("CFO", 30000);
Employee headFinance1 = new Employee("Head Finance. North Zone", 20000);
Employee headFinance2 = new Employee("Head Finance. West Zone", 22000);

Employee accountant1 = new Employee("Accountant1", 10000);
Employee accountant2 = new Employee("Accountant2", 9000);

Employee accountant3 = new Employee("Accountant3", 11000);
Employee accountant4 = new Employee("Accountant4", 12000);

CFO.add(headFinance1);
CFO.add(headFinance2);

headFinance1.add(accountant1);
headFinance1.add(accountant4);

headFinance2.add(accountant2);
headFinance2.add(accountant3);
}// End of class

Once we have filled the tree up, now we can get the tree for any employee and find out whether that employee has subordinates with the following condition.

Vector subOrdinates = emp.getSubordinates();
if (subOrdinates.size() != 0)
getTree(subOrdinates);
else
System.out.println("No Subordinates for the Employee: "+emp.getName());

Thus the Composite pattern allows you to create a tree like structure for simple and complex objects so they appear the same to the client.

No comments:

Post a Comment