Structural Design Pattern: Composite Pattern - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Structural Design Pattern: Composite Pattern

Share This
The Composite Pattern states that clients should be able to interact with items, regardless of whether these objects form a hierarchy of objects or not, in a generic manner.

The advantage of using the Composite Design Pattern is that it allows for the creation of complex hierarchical structures by treating individual objects and groups of objects uniformly.

  • It establishes class hierarchies that include both basic and intricate things. 
  • It facilitates the addition of new types of components. 
  • It has the advantage of having a flexible structure with easily controllable classes or interfaces.

Source code of Employee.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.t4b.test.java.dp.sp.cp;
import java.util.ArrayList;
import java.util.List;
class Employee {
private String name;
private String designation;
private List<Employee> subordinates;
public Employee(String name, String designation) {
this.name = name;
this.designation = designation;
subordinates = new ArrayList<Employee>();
}
public void addSubordinate(Employee e) {
subordinates.add(e);
}
public void removeSubordinate(Employee e) {
subordinates.remove(e);
}
public List<Employee> getSubordinates() {
return subordinates;
}
@Override
public String toString() {
return "Employee [name=" + name + ", designation=" + designation + ", subordinates=" + subordinates + "]";
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Source code of TestMain.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.t4b.test.java.dp.sp.cp;
public class TestMain {
public static void main(String[] args) {
Employee ceo = new Employee("Smith", "CEO");
Employee salesHead = new Employee("Johnson", "Sales");
Employee marketingHead = new Employee("Williams", "Marketing");
ceo.addSubordinate(salesHead);
ceo.addSubordinate(marketingHead);
Employee programmer = new Employee("Jones", "Programmer");
marketingHead.addSubordinate(programmer);
programmer = new Employee("Brown", "Programmer");
marketingHead.addSubordinate(programmer);
Employee tester = new Employee("Davis", "Tester");
salesHead.addSubordinate(tester);
tester = new Employee("Miller", "Tester");
salesHead.addSubordinate(tester);
System.out.println(ceo);
for (Employee e : ceo.getSubordinates()) {
System.out.println(e);
for (Employee employee : e.getSubordinates()) {
System.out.println(employee);
}
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.