Browser docs

Composite Entity

Intent

It is used to model, represent, and manage a set of persistent objects that are interrelated, rather than representing them as individual fine-grained entities.

Explanation

Real world example

For a console, there may be many interfaces that need to be managed and controlled. Using the composite entity pattern, dependent objects such as messages and signals can be combined together and controlled using a single object.

In plain words

Composite entity pattern allows a set of related objects to be represented and managed by a unified object.

Programmatic Example

We need a generic solution for the problem. To achieve this, let’s introduce a generic Composite Entity Pattern.

 1public abstract class DependentObject<T> {
 2
 3  T data;
 4
 5  public void setData(T message) {
 6    this.data = message;
 7  }
 8
 9  public T getData() {
10    return data;
11  }
12}
13
14public abstract class CoarseGrainedObject<T> {
15
16  DependentObject<T>[] dependentObjects;
17
18  public void setData(T... data) {
19    IntStream.range(0, data.length).forEach(i -> dependentObjects[i].setData(data[i]));
20  }
21
22  public T[] getData() {
23    return (T[]) Arrays.stream(dependentObjects).map(DependentObject::getData).toArray();
24  }
25}

The specialized composite entity console inherit from this base class as follows.

 1public class MessageDependentObject extends DependentObject<String> {
 2
 3}
 4
 5public class SignalDependentObject extends DependentObject<String> {
 6
 7}
 8
 9public class ConsoleCoarseGrainedObject extends CoarseGrainedObject<String> {
10
11  @Override
12  public String[] getData() {
13    super.getData();
14    return new String[]{
15        dependentObjects[0].getData(), dependentObjects[1].getData()
16    };
17  }
18
19  public void init() {
20    dependentObjects = new DependentObject[]{
21        new MessageDependentObject(), new SignalDependentObject()};
22  }
23}
24
25public class CompositeEntity {
26
27  private final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject();
28
29  public void setData(String message, String signal) {
30    console.setData(message, signal);
31  }
32
33  public String[] getData() {
34    return console.getData();
35  }
36}

Now managing the assignment of message and signal objects with the composite entity console.

1var console = new CompositeEntity();
2console.init();
3console.setData("No Danger", "Green Light");
4Arrays.stream(console.getData()).forEach(LOGGER::info);
5console.setData("Danger", "Red Light");
6Arrays.stream(console.getData()).forEach(LOGGER::info);

Class diagram

alt text

Applicability

Use the Composite Entity Pattern in the following situation:

  • You want to manage multiple dependency objects through one object to adjust the degree of granularity between objects. At the same time, the lifetime of dependency objects depends on a coarse-grained object.

Credits