I am trying to confirm my understanding of what the code would look like for association, aggregation & composition. So here goes..
Aggregation:
For two objects Foo
and Bar
we have:
Dependency:
class Foo
{
...
fooMethod(Bar bar){}
...
}
Association:
class Foo
{
private Bar bar;
...
}
Composition: (When Foo
dies so does Bar
)
class Foo
{
...
private Bar bar = new Bar();
...
}
Aggregation: (When Foo
dies, Bar
may live on)
class Foo
{
private List<Bar> bars;
}
The difference between aggregation and composition is pretty fuzzy and AFAIK relates to the logical existence of the "child" objects after the container is destroyed. Hence, in the case of aggregation the objects inside the container can still exist after the container object is destroyed, while in the case of composition design demands that they also get destroyed. Some analogies:
Car
object containing four Wheel
objects. Normally if you destroy the car (by calling some method to clean it up) you should also destroy the wheels in the process, since it makes little sense for them to exist outside the car (unless you move them to another Car
object). More realistically, a reader object wrapping an input stream will also close the inner stream when it gets closed itself. This is composition.Person
object contains (owns) a Radio
object. If the Person
dies, the Radio
may be inherited by another Person
i.e. it makes sense for it to exist without the original owner. More realistically, a list holding objects does not demand that all objects get disposed when the list itself is disposed. This is aggregation.Edit: After reading your links I'd be inclined to go with the first one, since it gives an explanation similar to mine.
Also association is merely invoking a method (sending a message) to another object via a reference to that object.