mercredi 17 mars 2021

Difference between aggregation and composition

I found the following two examples differentiating aggregation and composition in a java code
Composition

final class Car {

  private final Engine engine;

  Car(EngineSpecs specs) {
    engine = new Engine(specs);
  }

  void move() {
    engine.work();
  }
}

Aggregation

final class Car {

  private Engine engine;

  void setEngine(Engine engine) {
    this.engine = engine;
  }

  void move() {
    if (engine != null)
      engine.work();
  }
}

I have some doubts. I noticed the following points on these two
1 When two objects are aggregated, it looks similar to composition, the only
difference is that if the root object is destroyed, the other objects will not be destroyed.

  1. Could we then say that an aggregation is also a composition but not vice versa ?

  2. Since in aggregation a composition is involved, the only way for the objects to exist
    independently is to provide them from outside. Kind of like inject them rather then compose them
    from inside the root class. This sounds a lot like Dependency Injection principle.

Any comments on the above points or some more pointers ?
Also is aggregate pattern same as the aggregation ? I read several references which uses the term
invariant with aggregate pattern

Aucun commentaire:

Enregistrer un commentaire