Search code examples
javadesign-patternsaggregationdelegation

Why is it delegation rather than aggregation if the secondary object continues to exist even if the primary object is destroyed


I found this example in this SO for delegation. I fail to see why this not an aggregation relationship? The Secretary object continues to exist even if boss object is destroyed

public interface Worker() {
  public Result work();
}

public class Secretary() implements Worker {

   public Result work() {
     Result myResult = new Result();
     return myResult;
   }    
}

can someone explain why this is delegation but not aggregation?

public class Boss() implements Worker {

   private Secretary secretary;

   public Result work() {
     return secretary.work();
   }   
}

Solution

  • If it were aggregation then the aggregated object would have a subsidiary lifecycle to the container. I.e. if the container goes away, so does the contained object. From the Wikipedia page for Composition

    Composition is a kind of association where the composite object has sole responsibility for the disposition of the component parts. The relationship between the composite and the component is a strong “has a” relationship, as the composite object takes ownership of the component. This means the composite is responsible for the creation and destruction of the component parts.