Author - StudySection Post Views - 55 views
Salesforce Apex

Composite Pattern in Salesforce Apex

The composite design pattern in Salesforce Apex is where we implement nested objects of the same class. This pattern is used in the case of hierarchical structure. The data structure pattern of the composite pattern is tree type.

Problem:

In a company, there are many types of employees. The company wants to store employees’ data and their subordinates.

Solution:

To resolve this problem we need to implement the composite pattern because of the hierarchical employee structure.
public class EmployeeData {
private String name;
private String department;
private integer salary;
private List<Employee> subordinates;
// constructor
public EmployeeData (String name, String department, Integer salary) {
this.name = name;
this.department = department;
this.salary = salary;
subordinates = new List<Employee>();
}
public void add(EmployeeData e) {
subordinates.add(e);
}
public void remove(EmployeeData e) {
for(Integer i = subordinates.size() - 1; i >= 0; i--) {
if(subordinates[i].equals(e)) {
subordinates.remove(i);
}
}
}
public List<Employee> getSubordinates(){
return subordinates;
}
}
public class CompositePatternDemo {
public static void validateResult() {
EmployeeData CEO = new EmployeeData('John','CEO', 30000);
EmployeeData headSales = new EmployeeData('Robert','Head Sales', 20000);
EmployeeData headMarketing = new EmployeeData('Michel','Head Marketing', 20000);
EmployeeData clerk1 = new EmployeeData('Laura','Marketing', 10000);
EmployeeData clerk2 = new EmployeeData('Bob','Marketing', 10000);
EmployeeData salesExecutive1 = new EmployeeData('Richard','Sales', 10000);
EmployeeData salesExecutive2 = new EmployeeData('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.debug('CEO:' + CEO);
for (EmployeeData headEmployee : CEO.getSubordinates()) {
System.debug('Head Employee:' + headEmployee);
for (EmployeeData employee : headEmployee.getSubordinates()) {
System.debug('Simple Employee:' + employee);
}
}
}
}

jQuery allows the user to create powerful and dynamic webpages that run without any hiccup. With StudySection, you have the liberty to choose among beginner or expert level jQuery Certification Exams to help you excel in this career field.

Leave a Reply

Your email address will not be published.