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

StackOverflow https://stackoverflow.com/questions/19126891

Question

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();
   }   
}
Was it helpful?

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.

OTHER TIPS

It is both.

Boss is composed of (aggregates) Secretary, and delegates work() to Secretary.

If Boss was the last reference to Secretary then it becomes eligible for GC. But the code presented doesn't cover that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top