Aggregation
Aggregation is the other form of association and is similar to composition. In aggregation, a container object again has several references to other objects. But, Aggregation is looser than composition. The objects' life cycles are not bound to each other in aggregation. Thus, the referring object may get destroyed before/after the referenced object.
Let's add some more properties to the Vehicle
class to demonstrate aggregation.
1// Vehicle.js
2class Vehicle {
3 constructor() {
4 this.wheels = Array(4).fill(new Wheel());
5 this.doors = Array(4).fill(new Door());
6 this.seats = Array(4).fill(new Seat());
7 this.passengers = [];
8 }
9
10 getIn(person) {
11 this.passengers.push(person);
12 }
13
14 getOut(person) {
15 let index = this.passengers.indexOf(person);
16 if (index > -1) {
17 this.passengers.splice(index, 1);
18 }
19 }
20
21 move(a, b) {
22 // Moving
23 }
24}
In the above example, each Person
object that is inside the Vehicle
is not being created with the Vehicle
. When they get out of the Vehicle
, they are not destroyed. This is possible since there are other classes that also reference the Person
object. Let's see the main
method here.
1// Main.js
2class Main {
3 static transport(a, b, person) {
4 let vehicle = new Vehicle();
5 vehicle.getIn(person);
6 vehicle.move(a, b);
7 // Getting out of scope, vehicle gets destroyed
8 // But person object is still alive
9 }
10
11 main() {
12 // Person getting created before Vehicle
13 let person1 = new Person();
14 let vehicle = new Vehicle(); // All the Composition objects (door, wheel) getting created with Vehicle
15
16 // Aggregation happening here
17 vehicle.getIn(person1);
18
19 // Person getting created after Vehicle
20 let person2 = new Person();
21
22 // Another person object aggregating
23 vehicle.getIn(person2);
24
25 vehicle.getOut(person1);
26
27 Main.transport(new Place('A'), new Place('B'), person1);
28
29 // Everything getting destroyed here
30 }
31}
In the above example, we can see in the main
method that the Person
objects can be created regardless of whether Vehicle
instantiation occurs. In the transport
method, we can see that even if the Vehicle
object is created and then deleted, the Person
object is alive in the method and after that.