Friday, November 27, 2009

Composition vs. Aggregation

They both are within the context of OO design and both refer to a form of object ownership - one object contains one or many other objects.

The difference lays in the strictness of the ownership. For composition, it implies an ownership of lifetime. From implementation aspect, the compositor manages the lifetime of its containing objects. If the parent gets GCed, its composed objects are all gone away with it. Composition is thus of owning by value (does pass-by-value sound familiar?)

On the other hand, aggregation is a weaker form of ownership. In other words, if aggregator is dead (GCed), its aggregated objects will still happily live in the heap (memory heap). Under this context, aggregation is of owning by reference (Pass-by-reference as oppose to pass-by-value).

A code snippet for composition would look like this
class Compositor
{
Object obj1;
Object obj2;

public Compositor ()
{
this.obj1 = new Object();
this.obj2 = new Object();
}

}

Here is an example of aggregator
class Aggregator
{
Object obj1;
Object obj2;

public Aggregator (Object obj1, Object obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}

No comments: