DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Iterator Design Pattern In Java
  • Object Relational Behavioral Design Patterns in Java
  • Distribution Design Patterns in Java - Data Transfer Object (DTO) And Remote Facade Design Patterns
  • Context Object Design Pattern in Java: Introduction and Key Points

Trending

  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  • How to Practice TDD With Kotlin
  • Scalability 101: How to Build, Measure, and Improve It
  1. DZone
  2. Coding
  3. Languages
  4. Composite Design Pattern in Java

Composite Design Pattern in Java

Want to learn more about the composite design pattern in Java? Take a look at this tutorial to learn how to implement this design pattern in your project.

By 
Brijesh Saxena user avatar
Brijesh Saxena
DZone Core CORE ·
Updated Oct. 20, 20 · Tutorial
Likes (18)
Comment
Save
Tweet
Share
63.5K Views

Join the DZone community and get the full member experience.

Join For Free

Here I am with another useful design pattern for you — the Composite Design Pattern. I will try to point out the key features to remember while implementing the composite pattern for you.

Composite Design Pattern

The Composite Design Pattern is meant to "compose objects into a tree structure to represent part-whole hierarchies. Composite Pattern lets clients treat individual objects and compositions of objects uniformly".

  • The Composite Design patterns describe groups of objects that can be treated in the same way as a single instance of the same object type.
  • The Composite pattern allows us to "compose" objects into tree structures to represent part-whole hierarchies.
  • In addition, the Composite patterns also allow our clients to treat individual objects and compositions in the same way.
  • The Composite patterns allow us to have a tree structure for each node that performs a task.
  • In object-oriented programming, a Composite is an object designed as a composition of one-or-more similar objects, all exhibiting similar functionality. This is known as a “has-a” relationship between objects.

Below is the list of classes/objects used in the composite pattern, which has four :

  • Component – Component is the interface (or abstract class) for the composition of the objects and methods for accessing/processing its child or node components. It also implements a default interface to define common functionalities/behaviors for all component classes.
  • Leaf – The leaf class defines a concrete component class, which does not have any further composition. The leaf class implements the component interface. It performs the command/task at its end only.
  • Composite – The composite class defines a concrete component class, which stores its child components. The composite class implements the component interface. It forwards the command/task to the composite objects it contains. It may also perform additional operations before and after forwarding the command/task.
  • Client – The client class uses the component interface to interact/manipulate the objects in the composition (Leaf and Composite).

To better understand this, let's take a look at an example of employees working in an organization.

Steps

  • We create an interface to define functionalities we like to perform as composite and leaf objects. Below is the code of the Worker interface, which has methods for assignWork() and performWork(). The Work interface will act as a component of the composite pattern in the example.
Java
 




x


 
1
package org.trishinfotech.composite;
2
 
          
3
public interface Worker {
4
 
          
5
    void assignWork(Employee manager, Work work);
6
 
          
7
    void performWork();
8
}
9
 
          


The Work Class is defined as below: 

Java
 




xxxxxxxxxx
1
41


 
1
package org.trishinfotech.composite;
2
 
          
3
import java.util.ArrayList;
4
import java.util.List;
5
 
          
6
public class Work {
7
 
          
8
    private Calculator workType;
9
    private List<String> work = new ArrayList<String>();
10
 
          
11
    public Work(Calculator workType, List<String> work) {
12
        super();
13
        this.workType = workType;
14
        this.work = work;
15
    }
16
 
          
17
    public Calculator getWorkType() {
18
        return workType;
19
    }
20
 
          
21
    public void setWorkType(Calculator workType) {
22
        this.workType = workType;
23
    }
24
 
          
25
    public List<String> getWork() {
26
        return work;
27
    }
28
 
          
29
    public void setWork(List<String> work) {
30
        this.work = work;
31
    }
32
 
          
33
    @Override
34
    public String toString() {
35
        StringBuilder builder = new StringBuilder();
36
        builder.append("Work [workType=").append(workType).append(", work=").append(work).append("]");
37
        return builder.toString();
38
    }
39
 
          
40
}
41
 
          


To keep the example simple, Here I am dealing only with simple calculations like Factorial value and Palindrome and Armstrong check. Since Pandirome can be a string as well, I have kept work as String in theWork class. Below class defines the algorithms/formulas to perform Factorial, Palindrome and Armstrong. Here's the code for Calculator enum:

Java
 




xxxxxxxxxx
1
61


 
1
package org.trishinfotech.composite;
2
 
          
3
import java.math.BigInteger;
4
 
          
5
public enum Calculator {
6
 
          
7
    FACTORIAL {
8
        @Override
9
        public String calculate(String value) {
10
            String answer = "NA";
11
            try {
12
                long longValue = Long.parseLong(value);
13
                BigInteger factorialValue = BigInteger.valueOf(1);
14
                for (long i = 1; i <= longValue; i++) {
15
                    factorialValue = factorialValue.multiply(BigInteger.valueOf(i));
16
                }
17
                answer = factorialValue.toString();
18
            } catch (NumberFormatException exp) {
19
                System.out.println("Can't calculate factorial of " + value);
20
            }
21
            return answer;
22
        }
23
    },
24
 
          
25
    PALINDROME {
26
        @Override
27
        public String calculate(String value) {
28
            String answer = "false";
29
            if (value != null && !value.trim().isEmpty()) {
30
                String reverse = (new StringBuilder(value).reverse().toString());
31
                answer = Boolean.toString(reverse.equals(value));
32
            }
33
            return answer;
34
        }
35
    },
36
 
          
37
    ARMSTRONG {
38
        @Override
39
        public String calculate(String value) {
40
            String answer = "false";
41
            try {
42
                long longValue = Long.parseLong(value);
43
                long number = longValue;
44
                long armstrongValue = 0;
45
                while (number != 0) {
46
                    long temp = number % 10;
47
                    armstrongValue = armstrongValue + temp * temp * temp;
48
                    number /= 10;
49
                }
50
                answer = Boolean.toString(String.valueOf(armstrongValue).equals(value));
51
            } catch (NumberFormatException exp) {
52
                System.out.println("Can't calculate armstrong of " + value);
53
            }
54
            return answer;
55
        }
56
    };
57
 
          
58
    public abstract String calculate(String value);
59
 
          
60
}
61
 
          


I have created these algorithms as enums. To read more on Java-Enums, please refer to my article (Java Enums: How to Make Enums More Useful).

  • We will create an abstract class of Employee to carry the common code for all various concrete subclasses of the employees.
Java
 




xxxxxxxxxx
1
71


 
1
package org.trishinfotech.composite;
2
 
          
3
public abstract class Employee implements Worker {
4
 
          
5
    protected long employeeId;
6
    protected String employeeName;
7
    protected String designation;
8
    protected Department department;
9
 
          
10
    public Employee(long employeeId, String employeeName, String designation, Department department) {
11
        super();
12
        this.employeeId = employeeId;
13
        this.employeeName = employeeName;
14
        this.designation = designation;
15
        this.department = department;
16
    }
17
 
          
18
    public long getEmployeeId() {
19
        return employeeId;
20
    }
21
 
          
22
    public void setEmployeeId(long employeeId) {
23
        this.employeeId = employeeId;
24
    }
25
 
          
26
    public String getEmployeeName() {
27
        return employeeName;
28
    }
29
 
          
30
    public void setEmployeeName(String employeeName) {
31
        this.employeeName = employeeName;
32
    }
33
 
          
34
    public String getDesignation() {
35
        return designation;
36
    }
37
 
          
38
    public void setDesignation(String designation) {
39
        this.designation = designation;
40
    }
41
 
          
42
    public Department getDepartment() {
43
        return department;
44
    }
45
 
          
46
    public void setDepartment(Department department) {
47
        this.department = department;
48
    }
49
 
          
50
    public abstract int teamSize();
51
 
          
52
    public String fullDetails() {
53
        StringBuilder builder = new StringBuilder();
54
        builder.append("Employee [").append(employeeId).append(", ").append(employeeName).append(", ")
55
                .append(designation).append(", ").append(department).append(", Team=").append(teamSize()).append("]");
56
        return builder.toString();
57
    }
58
 
          
59
    public String shortDetails() {
60
        StringBuilder builder = new StringBuilder();
61
        builder.append("'").append(employeeName).append("'");
62
        return builder.toString();
63
    }
64
 
          
65
    @Override
66
    public String toString() {
67
        return shortDetails();
68
    }
69
 
          
70
}
71
 
          


The Employeeclass declares abstract method teamSize() which I will use to split the work load assigned from a manager to anEngineer. So teamSize() will will be 1 forEngineer where as it will give the number of employees theManager is managing.

TheEngineer class is as below:

Java
 




xxxxxxxxxx
1
38


 
1
package org.trishinfotech.composite;
2
 
          
3
import java.util.ArrayList;
4
import java.util.List;
5
 
          
6
public class Engineer extends Employee {
7
 
          
8
    private List<Work> works = new ArrayList<Work>();
9
 
          
10
    public Engineer(long employeeId, String employeeName, String designation, Department department) {
11
        super(employeeId, employeeName, designation, department);
12
    }
13
 
          
14
    @Override
15
    public int teamSize() {
16
        return 1;
17
    }
18
 
          
19
    @Override
20
    public void assignWork(Employee manager, Work work) {
21
        this.works.add(work);
22
        System.out.println(this + " has assigned work of '" + work + "' by manager " + manager);
23
    }
24
 
          
25
    @Override
26
    public void performWork() {
27
        System.out.println(this + " is performing work of '" + works + "'");
28
        works.stream().forEach(work -> {
29
            work.getWork().stream().forEach(value -> {
30
                Calculator calculator = work.getWorkType();
31
                System.out.println(this + " has result of work of '" + work + "' as : " + calculator.calculate(value));
32
            });
33
        });
34
        works.clear();
35
    }
36
 
          
37
}
38
 
          


  • We will create the Manager class to use as the composite object, and we will have another Employee object as a collection via the composition.

The Manager class is as below:

Java
 




xxxxxxxxxx
1
63


 
1
package org.trishinfotech.composite;
2
 
          
3
import java.util.ArrayList;
4
import java.util.List;
5
 
          
6
public class Manager extends Employee {
7
 
          
8
    List<Employee> managingEmployees = new ArrayList<Employee>();
9
 
          
10
    public Manager(long employeeId, String employeeName, String designation, Department department) {
11
        super(employeeId, employeeName, designation, department);
12
    }
13
 
          
14
    public boolean manages(Employee employee) {
15
        return managingEmployees.add(employee);
16
    }
17
 
          
18
    public boolean stopManaging(Employee employee) {
19
        return managingEmployees.remove(employee);
20
    }
21
 
          
22
    @Override
23
    public int teamSize() {
24
        return managingEmployees.stream().mapToInt(employee -> employee.teamSize()).sum();
25
    }
26
 
          
27
    @Override
28
    public void assignWork(Employee manager, Work work) {
29
        System.out.println(this + " has assigned work of '" + work + "' by manager " + manager);
30
        System.out.println();
31
        System.out.println(this + " distributing work '" + work + "' to managing-employees..");
32
        int fromIndex = 0;
33
        int toIndex = 0;
34
        int totalWork = work.getWork().size();
35
        List<String> assignWork = null;
36
        while (toIndex < totalWork) {
37
            for (Employee employee : managingEmployees) {
38
                System.out.println("Assigning to " + employee);
39
                int size = employee.teamSize();
40
                toIndex = fromIndex + size;
41
                assignWork = work.getWork().subList(fromIndex, toIndex);
42
                if (assignWork.isEmpty()) {
43
                    return;
44
                }
45
                employee.assignWork(this, new Work(work.getWorkType(), assignWork));
46
                fromIndex = toIndex;
47
            }
48
            break;
49
        }
50
    }
51
 
          
52
    @Override
53
    public void performWork() {
54
        System.out.println(this + " is asking his managing employees to perform assigned work");
55
        System.out.println();
56
        managingEmployees.stream().forEach(employee -> employee.performWork());
57
        System.out.println();
58
        System.out.println(this + " has completed assigned work with the help of his managing employees");
59
        System.out.println();
60
    }
61
 
          
62
}
63
 
          


  • We define Work in the property file instead of hard-coding into theMain class. The work.propertiesis defined as below:
Java
 




xxxxxxxxxx
1


 
1
Calculate.Palindrome=1234321, 12341234, ABCDEDCBA, 4567887654, XYZZYX, 45676543, 3456543
2
Calculate.Armstrong=153, 8208, 2104, 4210818, 345321, 32164049651, 876412347
3
Calculate.Factorial=20, 43, 15, 120, 543, 35, 456, 432, 350, 44, 26, 17, 8


  • The Main class usesWorkLoader class to load work from the work.properties. TheWorkLoader  class is defined as below:
Java
 




xxxxxxxxxx
1
43


 
1
package org.trishinfotech.composite;
2
 
          
3
import java.io.FileInputStream;
4
import java.io.IOException;
5
import java.io.InputStream;
6
import java.util.ArrayList;
7
import java.util.Arrays;
8
import java.util.List;
9
import java.util.Properties;
10
import java.util.Set;
11
 
          
12
public class WorkLoader {
13
 
          
14
    protected Properties properties = new Properties();
15
 
          
16
    public WorkLoader(String fileName) {
17
 
          
18
        try (InputStream input = new FileInputStream(fileName)) {
19
            // load a properties file
20
            properties.load(input);
21
        } catch (IOException exp) {
22
            exp.printStackTrace();
23
        }
24
    }
25
 
          
26
    public Properties getProperties() {
27
        return properties;
28
    }
29
 
          
30
    public List<Work> getWorkList() {
31
        List<Work> workList = new ArrayList<Work>();
32
        Set<Object> keys = properties.keySet();
33
        for (Object key : keys) {
34
            String workType = key.toString().substring("Calculate".length() + 1).toUpperCase();
35
            String values = properties.getProperty(key.toString());
36
            Work work = new Work(Calculator.valueOf(workType), Arrays.asList(values.split(", ")));
37
            workList.add(work);
38
        }
39
        return workList;
40
    }
41
 
          
42
}
43
 
          


  • In the end, we will write the Main class as the Client to execute and test our composite pattern code.
Java
 




xxxxxxxxxx
1
39


 
1
package org.trishinfotech.composite;
2
 
          
3
public class Main {
4
 
          
5
    public static void main(String[] args) {
6
        Engineer ajay = new Engineer(1001l, "Ajay", "Developer", Department.ENG);
7
        Engineer vijay = new Engineer(1002l, "Vijay", "SR. Developer", Department.ENG);
8
        Engineer jay = new Engineer(1003l, "Jay", "Lead", Department.ENG);
9
        Engineer martin = new Engineer(1004l, "Martin", "QA", Department.ENG);
10
        Manager kim = new Manager(1005l, "Kim", "Manager", Department.ENG);
11
        Engineer anders = new Engineer(1006l, "Andersen", "Developer", Department.ENG);
12
        Manager niels = new Manager(1007l, "Niels", "Sr. Manager", Department.ENG);
13
        Engineer robert = new Engineer(1008l, "Robert", "Developer", Department.ENG);
14
        Manager rachelle = new Manager(1009l, "Rachelle", "Product Manager", Department.ENG);
15
        Engineer shailesh = new Engineer(1010l, "Shailesh", "Engineer", Department.ENG);
16
 
          
17
        kim.manages(ajay);
18
        kim.manages(martin);
19
        kim.manages(vijay);
20
 
          
21
        niels.manages(jay);
22
        niels.manages(anders);
23
        niels.manages(shailesh);
24
 
          
25
        rachelle.manages(kim);
26
        rachelle.manages(robert);
27
        rachelle.manages(niels);
28
 
          
29
        WorkLoader workLoad = new WorkLoader("work.properties");
30
        workLoad.getWorkList().stream().forEach(work -> {
31
            rachelle.assignWork(rachelle, work);
32
        });
33
 
          
34
        rachelle.performWork();
35
 
          
36
    }
37
 
          
38
}
39
 
          


  • Below is the output of the program:
Java
 




xxxxxxxxxx
1
119


 
1
'Rachelle' has assigned work of 'Work [workType=FACTORIAL, work=[20, 43, 15, 120, 543, 35, 456, 432, 350, 44, 26, 17, 8]]' by manager 'Rachelle'
2
 
          
3
'Rachelle' distributing work 'Work [workType=FACTORIAL, work=[20, 43, 15, 120, 543, 35, 456, 432, 350, 44, 26, 17, 8]]' to managing-employees..
4
Assigning to 'Kim'
5
'Kim' has assigned work of 'Work [workType=FACTORIAL, work=[20, 43, 15]]' by manager 'Rachelle'
6
 
          
7
'Kim' distributing work 'Work [workType=FACTORIAL, work=[20, 43, 15]]' to managing-employees..
8
Assigning to 'Ajay'
9
'Ajay' has assigned work of 'Work [workType=FACTORIAL, work=[20]]' by manager 'Kim'
10
Assigning to 'Martin'
11
'Martin' has assigned work of 'Work [workType=FACTORIAL, work=[43]]' by manager 'Kim'
12
Assigning to 'Vijay'
13
'Vijay' has assigned work of 'Work [workType=FACTORIAL, work=[15]]' by manager 'Kim'
14
Assigning to 'Robert'
15
'Robert' has assigned work of 'Work [workType=FACTORIAL, work=[120]]' by manager 'Rachelle'
16
Assigning to 'Niels'
17
'Niels' has assigned work of 'Work [workType=FACTORIAL, work=[543, 35, 456]]' by manager 'Rachelle'
18
 
          
19
'Niels' distributing work 'Work [workType=FACTORIAL, work=[543, 35, 456]]' to managing-employees..
20
Assigning to 'Jay'
21
'Jay' has assigned work of 'Work [workType=FACTORIAL, work=[543]]' by manager 'Niels'
22
Assigning to 'Andersen'
23
'Andersen' has assigned work of 'Work [workType=FACTORIAL, work=[35]]' by manager 'Niels'
24
Assigning to 'Shailesh'
25
'Shailesh' has assigned work of 'Work [workType=FACTORIAL, work=[456]]' by manager 'Niels'
26
'Rachelle' has assigned work of 'Work [workType=PALINDROME, work=[1234321, 12341234, ABCDEDCBA, 4567887654, XYZZYX, 45676543, 3456543]]' by manager 'Rachelle'
27
 
          
28
'Rachelle' distributing work 'Work [workType=PALINDROME, work=[1234321, 12341234, ABCDEDCBA, 4567887654, XYZZYX, 45676543, 3456543]]' to managing-employees..
29
Assigning to 'Kim'
30
'Kim' has assigned work of 'Work [workType=PALINDROME, work=[1234321, 12341234, ABCDEDCBA]]' by manager 'Rachelle'
31
 
          
32
'Kim' distributing work 'Work [workType=PALINDROME, work=[1234321, 12341234, ABCDEDCBA]]' to managing-employees..
33
Assigning to 'Ajay'
34
'Ajay' has assigned work of 'Work [workType=PALINDROME, work=[1234321]]' by manager 'Kim'
35
Assigning to 'Martin'
36
'Martin' has assigned work of 'Work [workType=PALINDROME, work=[12341234]]' by manager 'Kim'
37
Assigning to 'Vijay'
38
'Vijay' has assigned work of 'Work [workType=PALINDROME, work=[ABCDEDCBA]]' by manager 'Kim'
39
Assigning to 'Robert'
40
'Robert' has assigned work of 'Work [workType=PALINDROME, work=[4567887654]]' by manager 'Rachelle'
41
Assigning to 'Niels'
42
'Niels' has assigned work of 'Work [workType=PALINDROME, work=[XYZZYX, 45676543, 3456543]]' by manager 'Rachelle'
43
 
          
44
'Niels' distributing work 'Work [workType=PALINDROME, work=[XYZZYX, 45676543, 3456543]]' to managing-employees..
45
Assigning to 'Jay'
46
'Jay' has assigned work of 'Work [workType=PALINDROME, work=[XYZZYX]]' by manager 'Niels'
47
Assigning to 'Andersen'
48
'Andersen' has assigned work of 'Work [workType=PALINDROME, work=[45676543]]' by manager 'Niels'
49
Assigning to 'Shailesh'
50
'Shailesh' has assigned work of 'Work [workType=PALINDROME, work=[3456543]]' by manager 'Niels'
51
'Rachelle' has assigned work of 'Work [workType=ARMSTRONG, work=[153, 8208, 2104, 4210818, 345321, 32164049651, 876412347]]' by manager 'Rachelle'
52
 
          
53
'Rachelle' distributing work 'Work [workType=ARMSTRONG, work=[153, 8208, 2104, 4210818, 345321, 32164049651, 876412347]]' to managing-employees..
54
Assigning to 'Kim'
55
'Kim' has assigned work of 'Work [workType=ARMSTRONG, work=[153, 8208, 2104]]' by manager 'Rachelle'
56
 
          
57
'Kim' distributing work 'Work [workType=ARMSTRONG, work=[153, 8208, 2104]]' to managing-employees..
58
Assigning to 'Ajay'
59
'Ajay' has assigned work of 'Work [workType=ARMSTRONG, work=[153]]' by manager 'Kim'
60
Assigning to 'Martin'
61
'Martin' has assigned work of 'Work [workType=ARMSTRONG, work=[8208]]' by manager 'Kim'
62
Assigning to 'Vijay'
63
'Vijay' has assigned work of 'Work [workType=ARMSTRONG, work=[2104]]' by manager 'Kim'
64
Assigning to 'Robert'
65
'Robert' has assigned work of 'Work [workType=ARMSTRONG, work=[4210818]]' by manager 'Rachelle'
66
Assigning to 'Niels'
67
'Niels' has assigned work of 'Work [workType=ARMSTRONG, work=[345321, 32164049651, 876412347]]' by manager 'Rachelle'
68
 
          
69
'Niels' distributing work 'Work [workType=ARMSTRONG, work=[345321, 32164049651, 876412347]]' to managing-employees..
70
Assigning to 'Jay'
71
'Jay' has assigned work of 'Work [workType=ARMSTRONG, work=[345321]]' by manager 'Niels'
72
Assigning to 'Andersen'
73
'Andersen' has assigned work of 'Work [workType=ARMSTRONG, work=[32164049651]]' by manager 'Niels'
74
Assigning to 'Shailesh'
75
'Shailesh' has assigned work of 'Work [workType=ARMSTRONG, work=[876412347]]' by manager 'Niels'
76
'Rachelle' is asking his managing employees to perform assigned work
77
 
          
78
'Kim' is asking his managing employees to perform assigned work
79
 
          
80
'Ajay' is performing work of '[Work [workType=FACTORIAL, work=[20]], Work [workType=PALINDROME, work=[1234321]], Work [workType=ARMSTRONG, work=[153]]]'
81
'Ajay' has result of work of 'Work [workType=FACTORIAL, work=[20]]' as : 2432902008176640000
82
'Ajay' has result of work of 'Work [workType=PALINDROME, work=[1234321]]' as : true
83
'Ajay' has result of work of 'Work [workType=ARMSTRONG, work=[153]]' as : true
84
'Martin' is performing work of '[Work [workType=FACTORIAL, work=[43]], Work [workType=PALINDROME, work=[12341234]], Work [workType=ARMSTRONG, work=[8208]]]'
85
'Martin' has result of work of 'Work [workType=FACTORIAL, work=[43]]' as : 60415263063373835637355132068513997507264512000000000
86
'Martin' has result of work of 'Work [workType=PALINDROME, work=[12341234]]' as : false
87
'Martin' has result of work of 'Work [workType=ARMSTRONG, work=[8208]]' as : false
88
'Vijay' is performing work of '[Work [workType=FACTORIAL, work=[15]], Work [workType=PALINDROME, work=[ABCDEDCBA]], Work [workType=ARMSTRONG, work=[2104]]]'
89
'Vijay' has result of work of 'Work [workType=FACTORIAL, work=[15]]' as : 1307674368000
90
'Vijay' has result of work of 'Work [workType=PALINDROME, work=[ABCDEDCBA]]' as : true
91
'Vijay' has result of work of 'Work [workType=ARMSTRONG, work=[2104]]' as : false
92
 
          
93
'Kim' has completed assigned work with the help of his managing employees
94
 
          
95
'Robert' is performing work of '[Work [workType=FACTORIAL, work=[120]], Work [workType=PALINDROME, work=[4567887654]], Work [workType=ARMSTRONG, work=[4210818]]]'
96
'Robert' has result of work of 'Work [workType=FACTORIAL, work=[120]]' as : 6689502913449127057588118054090372586752746333138029810295671352301633557244962989366874165271984981308157637893214090552534408589408121859898481114389650005964960521256960000000000000000000000000000
97
'Robert' has result of work of 'Work [workType=PALINDROME, work=[4567887654]]' as : true
98
'Robert' has result of work of 'Work [workType=ARMSTRONG, work=[4210818]]' as : false
99
'Niels' is asking his managing employees to perform assigned work
100
 
          
101
'Jay' is performing work of '[Work [workType=FACTORIAL, work=[543]], Work [workType=PALINDROME, work=[XYZZYX]], Work [workType=ARMSTRONG, work=[345321]]]'
102
'Jay' has result of work of 'Work [workType=FACTORIAL, work=[543]]' as : 872891556790260456843586366934462570217404467584986862157951660218033476207283552939973350537069217537549478114229971312262991181125700413163606116971183695586311579361173915852193241844683585564114537080099157013082576149573523335369738442355599816710804068865355684599942047453968407440725166640261015140054933542126214585902983116193907129111747665196041855032660956095883694974186998924247749529335931094092429725640658310042199668214202637924631140057800119930627800378541111012271243379033822559451085315416955672912791395237932595257653475479021208979154389591618595449855779925751308303314870067464075830210893226767964127916083986194604372529850059441599156750579670067110415997949767860963439005485252514342425180564330056392659552281473502353159284918610493411467800558076001750687023376509841526414457026571388047691226042613278047076078395826335028468047405871941546558134196554638340479908186429178241794558954878506078646531853505428187507441610683354213870320835243780540993795316813622383436151335642255741817696689682127415809984693167490611336830354021351607247261703154384913620088006020923947745280000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
103
'Jay' has result of work of 'Work [workType=PALINDROME, work=[XYZZYX]]' as : true
104
'Jay' has result of work of 'Work [workType=ARMSTRONG, work=[345321]]' as : false
105
'Andersen' is performing work of '[Work [workType=FACTORIAL, work=[35]], Work [workType=PALINDROME, work=[45676543]], Work [workType=ARMSTRONG, work=[32164049651]]]'
106
'Andersen' has result of work of 'Work [workType=FACTORIAL, work=[35]]' as : 10333147966386144929666651337523200000000
107
'Andersen' has result of work of 'Work [workType=PALINDROME, work=[45676543]]' as : false
108
'Andersen' has result of work of 'Work [workType=ARMSTRONG, work=[32164049651]]' as : false
109
'Shailesh' is performing work of '[Work [workType=FACTORIAL, work=[456]], Work [workType=PALINDROME, work=[3456543]], Work [workType=ARMSTRONG, work=[876412347]]]'
110
'Shailesh' has result of work of 'Work [workType=FACTORIAL, work=[456]]' as : 150777392777717065903328562798297482932764849966301315324902295697797980802999492049275470580840593582700556154654997912467653672836190567363944536581444396786039028419417159553169852939652733499484374432647121409002713034716885273557660568294514238651304204026421026217797122437474581042706674997505548774529387552185264469304745879944335896334980134727576771262477699704913814778801164976379963316514713032786305083016847394455111607701177156363125206697642497352441989049637406799105387152093299654856194446887474831405921359722324720996553956200165400519069670468845686118517860926559421327845227712982865242890852011587912148558934925229259778865164753102371910801614732061965104129730561590839408147446252948841011789641706225763887234100676084552005497753764496546383864694159909979495432469993306110242973486330432796522331628915418533758582252153753291412897349335363154308911927972242304805109760000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
111
'Shailesh' has result of work of 'Work [workType=PALINDROME, work=[3456543]]' as : true
112
'Shailesh' has result of work of 'Work [workType=ARMSTRONG, work=[876412347]]' as : false
113
 
          
114
'Niels' has completed assigned work with the help of his managing employees
115
 
          
116
 
          
117
'Rachelle' has completed assigned work with the help of his managing employees
118
 
          
119
 
          


Here, I haven't use concurrency to keep the example simple. Please feel free to enhance the example as per your choice at your end.

Source Code can be found here: Composite-Design-Pattern-Sample-Code 

Liked this article? Don't forget to press that like button. Happy coding!

Need more articles on design patterns? Check out these useful posts:

  • Null Object Pattern in Java
  • Using the Adapter Design Pattern in Java
  • Using the Bridge Design Pattern in Java
  • Strategy vs. Factory Design Patterns in Java
  • Decorator Design Pattern in Java
  • How to Use Singleton Design Pattern in Java
  • Singleton Design Pattern: Making Singleton More Effective in Java
  • Java Enums: How to Make Enums More Useful
  • Java Enums: How to Use Configurable Sorting Fields
Java (programming language) Design Object (computer science) Composite pattern Interface (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Iterator Design Pattern In Java
  • Object Relational Behavioral Design Patterns in Java
  • Distribution Design Patterns in Java - Data Transfer Object (DTO) And Remote Facade Design Patterns
  • Context Object Design Pattern in Java: Introduction and Key Points

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!