Distinguishing between delegation, composition and aggregation (Java OO Design)

Viewed 43623

I am facing a continuing problem distinguishing delegation, composition and aggregation from each other, and identifying the cases where it's the best to use one over the other.

I have consulted a Java OO Analysis and Design book, but my confusion still remains. The main explanation is this:

Delegation: When my object uses another object's functionality as is without changing it.

Composition: My object consists of other objects which in turn cannot exist after my object is destroyed-garbage collected.

Aggregation: My object consists of other objects which can live even after my object is destroyed.

Is it possible to have a few simple examples demonstrating each case, and the reasoning behind them? How else can these examples be demonstrated other than my object simply having a reference to another object(s)?

5 Answers

In a very simple sentence I can say:

Delegation is: delegate behaviour to other class when you do not want to change it. by change I mean during run time. for example you delegate driver to car class that driver wont change while driving.

Composition is: when you want to use behaviour of family of classes (one or more classes, that implements an interface) that you might change during run time. but you should consider these classes can not exist with out main classes, such as rooms of a hotel. If you remove hotel all rooms of hotel will not exist.

Aggregation is: same as composition but classes can exist without main class.

Related