Thứ Bảy, 1 tháng 8, 2009

UML: aggregation v.s composition

Assume we have above class diagram. The relationship b/w CardList and Card is aggregation, and the one b/w Deck and CardList is composition.

The main difference b/w aggregation and composition is:
- Aggregation: Card can independently exist with CardList. This means when CardList object is destroyed, Card object is still alive until we destroy it explicitly.
The generated code may looks like
class CardList
{
//some code
Card *_contents[];
//some code
}
'Coz _contents is an array of
pointer, it independently exist with CardList. Therefore, in aggregation relationship, we MUST call delete to avoid memory leak.

- Composition: CardList life depends on Deck. This means when a Deck object is destroyed, CardList object also destroyed.
The generated code may looks like
class Deck
{
//some code
CardList _cards;
//some code
}
'Coz _cards is an
object (NOT a pointer), it will be destroyed when a Deck object destroyed. Therefore, with composition relationship, we don't care about delete contained object.

Không có nhận xét nào:

Đăng nhận xét