2

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();
   }   
}
Community
  • 1
  • 1
brain storm
  • 30,124
  • 69
  • 225
  • 393
  • The Boss "uses" secretary to do work (not good when reading it, though), so it is aggregation relationship, from relation perpective. But "how" the Boss do the work and giving result, from the method references, is considered as "Delegation". It is bad in Java does not has delegation-specific entity such as `Action` or `Func<>` in C#, so the only way to do delegation is by injecting an object to do the delegation... – Fendy Oct 02 '13 at 08:44
  • Possible duplicate of [distinguishing between delegation, composition and aggregation (java OO design)](http://stackoverflow.com/questions/1384426/distinguishing-between-delegation-composition-and-aggregation-java-oo-design) – Raedwald Feb 25 '16 at 12:54

2 Answers2

1

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.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
-1

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.

matthudson
  • 182
  • 6
  • Where Boss calls secretary.work(), that is delegation. Where it defines a private Secretary, that is composition aka aggregation. These patterns overlap in this implementation, they are not mutually exclusive. – matthudson Oct 01 '13 at 22:26