https://dzone.com/articles/composite-design-pattern-in-java-1

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

  • 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.
  • 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 Work interface, which has methods for assignWork() and performWork(). The Work interface will act as a component of the composite pattern in the example.
package design.composite;

public interface Work {

      void assignWork(Employee manager, String work);
void performWork();
}
  • We will create an abstract class of Employee to carry the common code for all various concrete subclasses of the employees.
package design.composite;

public abstract class Employee implements Work {

      protected long employeeId;
protected String employeeName;
protected String designation;
protected Department department; public Employee(long employeeId, String employeeName, String designation, Department department) {
super();
this.employeeId = employeeId;
this.employeeName = employeeName;
this.designation = designation;
this.department = department;
} public long getEmployeeId() {
return employeeId;
} public void setEmployeeId(long employeeId) {
this.employeeId = employeeId;
} public String getEmployeeName() {
return employeeName;
} public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
} public String getDesignation() {
return designation;
} public void setDesignation(String designation) {
this.designation = designation;
} public Department getDepartment() {
return department;
} public void setDepartment(Department department) {
this.department = department;
} @Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Employee [").append(employeeId)
.append(", ").append(employeeName)
.append(", ").append(Designation)
.append(", ").append(department)
.append("]");
return builder.toString();
} }
  • Now, we will create two concrete subclasses of the Employee — Manager and Engineer. For this, I am keeping the example simple to keep a focus on the pattern.
  • We will create the Engineer class to use as the Leaf object and, hence, does not have any other employee object as a reference via composition.
package design.composite;

public class Engineer extends Employee {

        private String work;

        public Engineer(long employeeId, String employeeName, String designation, Department department) {
super(employeeId, employeeName, designation, department);
} @Override
public void assignWork(Employee manager, String work) {
this.work = work;
System.out.println(this + " has assigned work of '" + work + "' by manager " + manager);
} @Override
public void performWork() {
System.out.println(this + " is performing work of '" + work + "'");
} }
  • 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.
package design.composite;

import java.util.ArrayList;
import java.util.List; public class Manager extends Employee { protected List<Employee> managingEmployees = new ArrayList<Employee>(); public Manager(long employeeId, String employeeName, String designation, Department department) {
super(employeeId, employeeName, designation, department);
} public boolean manages(Employee employee) {
return managingEmployees.add(employee);
} public boolean stopManaging(Employee employee) {
return managingEmployees.remove(employee);
} @Override
public void assignWork(Employee manager, String work) {
System.out.println(this + " has assigned work of '" + work + "' by manager " + manager);
System.out.println();
System.out.println(this + " distributing work '" + work + "' to managing-employees..");
managingEmployees.stream().forEach(employee -> {
System.out.println("Assigning to " + employee);
employee.assignWork(this, work);
});
System.out.println();
System.out.println(this + " distributed work of '" + work + "'");
System.out.println();
} @Override
public void performWork() {
System.out.println(this + " is asking his managing employees to perfom assigned work");
System.out.println();
managingEmployees.stream().forEach(employee -> employee.performWork());
System.out.println();
System.out.println(this + " has completed assigned work with the help of his manahging employees");
System.out.println();
} }
  • In the end, we will write the Main class as the Clien to execute and test our composite pattern code.
package design.composite;

public class Main {

public static void main(String[] args) {
Engineer ajay = new Engineer(1001l, "Ajay", "Developer", Department.ENG);
Engineer vijay = new Engineer(1002l, "Vijay", "SR. Developer", Department.ENG);
Engineer jay = new Engineer(1003l, "Jay", "Lead", Department.ENG);
Engineer martin = new Engineer(1004l, "Martin", "QA", Department.ENG);
Manager kim = new Manager(1005l, "Kim", "Manager", Department.ENG);
Engineer anders = new Engineer(1006l, "Andersen", "Developer", Department.ENG);
Manager niels = new Manager(1007l, "Niels", "Sr. Manager", Department.ENG);
Engineer robert = new Engineer(1008l, "Robert", "Developer", Department.ENG);
Manager rachelle = new Manager(1009l, "Rachelle", "Product Manager", Department.ENG);
Engineer shailesh = new Engineer(1010l, "Shailesh", "Engineer", Department.ENG); kim.manages(ajay);
kim.manages(martin);
kim.manages(vijay); niels.manages(jay);
niels.manages(anders);
niels.manages(shailesh); rachelle.manages(kim);
rachelle.manages(robert);
rachelle.manages(niels); rachelle.assignWork(rachelle, "develop web-service code for Product Catalogue"); rachelle.performWork();
} }
  • Below is the output of the program:
Employee [1009, Rachelle, Product Manager, ENG] has assigned work of 'develop web-service code for Product Catalogue' by manager Employee [1009, Rachelle, Product Manager, ENG]

Employee [1009, Rachelle, Product Manager, ENG] distributing work 'develop web-service code for Product Catalogue' to managing-employees..
Assigning to Employee [1005, Kim, Manager, ENG]
Employee [1005, Kim, Manager, ENG] has assigned work of 'develop web-service code for Product Catalogue' by manager Employee [1009, Rachelle, Product Manager, ENG] Employee [1005, Kim, Manager, ENG] distributing work 'develop web-service code for Product Catalogue' to managing-employees..
Assigning to Employee [1001, Ajay, Developer, ENG]
Employee [1001, Ajay, Developer, ENG] has assigned work of 'develop web-service code for Product Catalogue' by manager Employee [1005, Kim, Manager, ENG]
Assigning to Employee [1004, Martin, QA, ENG]
Employee [1004, Martin, QA, ENG] has assigned work of 'develop web-service code for Product Catalogue' by manager Employee [1005, Kim, Manager, ENG]
Assigning to Employee [1002, Vijay, SR. Developer, ENG]
Employee [1002, Vijay, SR. Developer, ENG] has assigned work of 'develop web-service code for Product Catalogue' by manager Employee [1005, Kim, Manager, ENG] Employee [1005, Kim, Manager, ENG] distributed work of 'develop web-service code for Product Catalogue' Assigning to Employee [1008, Robert, Developer, ENG]
Employee [1008, Robert, Developer, ENG] has assigned work of 'develop web-service code for Product Catalogue' by manager Employee [1009, Rachelle, Product Manager, ENG]
Assigning to Employee [1007, Niels, Sr. Manager, ENG]
Employee [1007, Niels, Sr. Manager, ENG] has assigned work of 'develop web-service code for Product Catalogue' by manager Employee [1009, Rachelle, Product Manager, ENG] Employee [1007, Niels, Sr. Manager, ENG] distributing work 'develop web-service code for Product Catalogue' to managing-employees..
Assigning to Employee [1003, Jay, Lead, ENG]
Employee [1003, Jay, Lead, ENG] has assigned work of 'develop web-service code for Product Catalogue' by manager Employee [1007, Niels, Sr. Manager, ENG]
Assigning to Employee [1006, Andersen, Developer, ENG]
Employee [1006, Andersen, Developer, ENG] has assigned work of 'develop web-service code for Product Catalogue' by manager Employee [1007, Niels, Sr. Manager, ENG]
Assigning to Employee [1010, Shailesh, Engineer, ENG]
Employee [1010, Shailesh, Engineer, ENG] has assigned work of 'develop web-service code for Product Catalogue' by manager Employee [1007, Niels, Sr. Manager, ENG] Employee [1007, Niels, Sr. Manager, ENG] distributed work of 'develop web-service code for Product Catalogue' Employee [1009, Rachelle, Product Manager, ENG] distributed work of 'develop web-service code for Product Catalogue' Employee [1009, Rachelle, Product Manager, ENG] is asking his managing employees to perfom assigned work Employee [1005, Kim, Manager, ENG] is asking his managing employees to perfom assigned work Employee [1001, Ajay, Developer, ENG] is performing work of 'develop web-service code for Product Catalogue'
Employee [1004, Martin, QA, ENG] is performing work of 'develop web-service code for Product Catalogue'
Employee [1002, Vijay, SR. Developer, ENG] is performing work of 'develop web-service code for Product Catalogue' Employee [1005, Kim, Manager, ENG] has completed assigned work with the help of his manahging employees Employee [1008, Robert, Developer, ENG] is performing work of 'develop web-service code for Product Catalogue'
Employee [1007, Niels, Sr. Manager, ENG] is asking his managing employees to perfom assigned work Employee [1003, Jay, Lead, ENG] is performing work of 'develop web-service code for Product Catalogue'
Employee [1006, Andersen, Developer, ENG] is performing work of 'develop web-service code for Product Catalogue'
Employee [1010, Shailesh, Engineer, ENG] is performing work of 'develop web-service code for Product Catalogue' Employee [1007, Niels, Sr. Manager, ENG] has completed assigned work with the help of his manahging employees Employee [1009, Rachelle, Product Manager, ENG] has completed assigned work with the help of his manahging employees

Composite Design Pattern in Java--转的更多相关文章

  1. Template Method Design Pattern in Java

    Template Method is a behavioral design pattern and it’s used to create a method stub and deferring s ...

  2. Composite Design Pattern 设计模式组合

    设计模式组合,它能够更类组合在一类,形成一个树状结构. #include <set> #include <iostream> #include <string> u ...

  3. Chain Of Responsibility Design Pattern Example

    Avoid coupling the sender of a request to the receiver by giving more than one object a chance to ha ...

  4. Design Pattern - Service Locator Pattern--转载

    原文地址:http://www.tutorialspoint.com/design_pattern/service_locator_pattern.htm The service locator de ...

  5. java设计模式大全 Design pattern samples in Java(最经典最全的资料)

    java设计模式大全 Design pattern samples in Java(最经典最全的资料) 2015年06月19日 13:10:58 阅读数:11100 Design pattern sa ...

  6. [Java] Design Pattern:Code Shape - manage your code shape

    [Java] Design Pattern:Code Shape - manage your code shape Code Shape Design Pattern Here I will intr ...

  7. java design pattern - adapter pattern

    场景 适配器模式 总结 参考资料 场景 在编程中我们经常会遇到驴头不对马嘴的情况,比如以前是继承A的接口的对象,现在外部调用的时候需要该对象已B接口的形式来调用 ,这个时候我们可以让对象同时集成A和B ...

  8. [转]Design Pattern Interview Questions - Part 4

    Bridge Pattern, Composite Pattern, Decorator Pattern, Facade Pattern, COR Pattern, Proxy Pattern, te ...

  9. [转]Design Pattern Interview Questions - Part 1

    Factory, Abstract factory, prototype pattern (B) What are design patterns? (A) Can you explain facto ...

随机推荐

  1. 关于使用idea的一些小技巧

    1:idea与git同步以后查看修改变化: file --setting--versioncontorller

  2. spring @Async 线程池使用

    最近公司项目正逐渐从dubbo向springCloud转型,在本次新开发的需求中,全部使用springcloud进行,在使用时线程池,考虑使用spring封装的线程池,现将本次使用心得及内容记录下来 ...

  3. LoadRunner---杂问题&接口测试

    问题1] 响应时间是系统完成事务执行准备后所采集的时间戳和系统完成待执行事务后所采集的时间戳之间的时间间隔,是衡量特定类型应用事务性能的重要指标,标志了用户执行一项操作大致需要多长时间.[问题2] 系 ...

  4. 基于CAS的单点登录实战(2)-- 搭建cas的php客户端

    在这之前已经搭好了CAS服务端 基于CAS的单点登录实战(1)-- 搭建cas服务器 PHP-Client php-Client是官方支持的,去官网下个最新版就好了.phpCAS 接入很简单,解压放到 ...

  5. 入参为json类型的接口测试示例

    一.接口文档内容 二.使用postman(入参为json类型) 如下部分内容即是json串: { "name":"刘星", "grade": ...

  6. 洛谷P2510 [HAOI2008]下落的圆盘(计算几何)

    题面 传送门 题解 对于每个圆,我们单独计算它被覆盖的周长是多少 只有相交的情况需要考虑,我们需要知道相交的那段圆弧的角度,发现其中一个交点和两个圆的圆心可以构成一个三角形且三边都已经知道了,那么我们 ...

  7. promise思考

    我写了三个单元块,分别对应三种业务场景 let query;query = (url) => { url=url||"传递的参数为空"; return new Promise ...

  8. Effective Java 3rd.Edition 翻译

    推荐序 前言 致谢 第一章 引言 第二章 创建和销毁对象 第1项:用静态工厂方法代替构造器 第2项:遇到多个构造器参数时要考虑使用构建器 第3项:用私有构造器或者枚举类型强化Singleton属性 第 ...

  9. 请设计实现一个商城系统开发v2.0【代码优化】

    #!/usr/bin/env python 优化的部分:1.改用字典取键,来调用函数[原来是用if-else判断] [补充]:也可以用列表,按索引取,可以在列表最前面加一个“”任意元素,凑成一个.就和 ...

  10. 创建逻辑卷LVM以及swap分区

    #!/bin/bash ##创建逻辑卷LVM /dev/mapper/lvm_data-data### ###default 大小为500G,但是LV一般会比500略小################ ...