Distinguishing Between Delegation Composition And Aggregation
09-05-2014
Delegation
When clients of A call method, class A delegates the method call to B.
Rationale. Class A can inherit from one class, but expose behaviours that belong elsewhere.
Further Study. http://beust.com/java-delegation.html
Composition
Once there are no more references to a particular instance of class A, its instance of class B is destroyed.
Rationale. Allows classes to define behaviours and attributes in a modular fashion.
Further Study. http://www.artima.com/designtechniques/compoinh.html
Aggregation
Once there are no more references to a particular instance of class A, its instance of class B will not be destroyed. In this example, both A and C must be garbage collected before B will be destroyed.
Rationale. Allows instances to reuse objects.
Further Study. http://faq.javaranch.com/java/AssociationVsAggregationVsComposition
Demonstration Without References
The names given to these simple patterns are defined by their referential relationships.
public class A {
private B b = new B();
public void method() {
b.method();
}
}
When clients of A call method, class A delegates the method call to B.
Rationale. Class A can inherit from one class, but expose behaviours that belong elsewhere.
Further Study. http://beust.com/java-delegation.html
Composition
public class A {
private B b = new B();
public A() {
}
}
Once there are no more references to a particular instance of class A, its instance of class B is destroyed.
Rationale. Allows classes to define behaviours and attributes in a modular fashion.
Further Study. http://www.artima.com/designtechniques/compoinh.html
Aggregation
public class A {
private B b;
public A( B b ) {
this.b = b;
}
}
public class C {
private B b = new B();
public C() {
A a = new A( this.b );
}
}
Once there are no more references to a particular instance of class A, its instance of class B will not be destroyed. In this example, both A and C must be garbage collected before B will be destroyed.
Rationale. Allows instances to reuse objects.
Further Study. http://faq.javaranch.com/java/AssociationVsAggregationVsComposition
Demonstration Without References
The names given to these simple patterns are defined by their referential relationships.