Composite design pattern is the part of structural design pattern .
When we need a composite object what will maintain a tree structure then we can use composite design pattern .
let's see an example . We want to develop our company organogram -
Project managers and sales managers works under the CTO. Developer works under the Project managers. Sales persons works under the sales manager.
public class Employee {
private String name;
private String department;
private int salary;
List<Employee> suborddinates;
public Employee(String name, String department, int salary) {
this.name = name;
this.department = department;
this.salary = salary;
suborddinates = new ArrayList<Employee>();
}
public void addSubordinates(Employee employee) {
suborddinates.add(employee);
}
public List<Employee> getSubordinates() {
return suborddinates;
}
@Override
public String toString() {
return "Employee [name=" + name + ", department=" + department + ", salary=" + salary + "]";
}
}
//Main class
public class MainApp {
public static void main(String[] args) {
Employee cto = new Employee("msr", "CTO", 100000);
Employee salesManager = new Employee("Hera", "Sales Manager", 80000);
Employee productManager = new Employee("Shahin", "Product Manager", 80000);
Employee sales1 = new Employee("makku", "Sales", 10000);
Employee sales2 = new Employee("Rumana", "Sales", 20000);
Employee dev1 = new Employee("lokman", "Developer", 60000);
Employee dev2 = new Employee("Sahabur", "Developer", 60000);
cto.addSubordinates(productManager);
cto.addSubordinates(salesManager);
productManager.addSubordinates(dev1);
productManager.addSubordinates(dev2);
salesManager.addSubordinates(sales2);
salesManager.addSubordinates(sales1);
System.out.println(cto.toString());
for (Employee manager : cto.getSubordinates()) {
System.out.println(manager.toString());
for (Employee junior : manager.getSubordinates()) {
System.out.println(junior.toString());
}
}
//output
Employee [name=msr, department=CTO, salary=100000]
Employee [name=Shahin, department=Product Manager, salary=80000]
Employee [name=lokman, department=Developer, salary=60000]
Employee [name=Sahabur, department=Developer, salary=60000]
Employee [name=Hera, department=Sales Manager, salary=80000]
Employee [name=Rumana, department=Sales, salary=20000]
Employee [name=makku, department=Sales, salary=10000]
No comments:
Post a Comment