Reputation: 31
I'm doing an assignment on class diagram and the following shows the association between classes Order
and Menu Item
. Should the link be aggregation (weak) or composition (strong)?
I'm confused because I've seen example showing aggregation. I felt it should be composition as an Order
must have at least 1 Menu Item
added. Am I wrong?
Upvotes: 2
Views: 5702
Reputation: 6175
A lot is dependent on context. Let's use an example that should clarify the difference for you.
Suppose you are assembling a Car object in a car factory. The Car object has two Axle objects, four Wheel objects, a Motor object, and so on. All of those objects only have meaning within the context of the entire car (once you put them in, they stay there). That's composition.
Now, suppose you have a Car object in a junkyard. The Car object has the same stuff, but you can pull wheels or axles or the motor out of it and sell them separately. In that case, each part has a lifetime separate from that of the car. That's aggregation.
Upvotes: 0
Reputation: 18009
Should the link be aggregation (weak) or composition (strong)?
It can be both. The main difference is:
In case it's a composition:
The MenuItem objects are destructed as soon as the Order object is destructed.
C++ example:
class Order {
MenuItem menus[NUMBER_OF_MENUS];
};
In case it's a aggregation:
The lifetime of the MenuItem objects is independent of the Order object lifetime.
C++ example:
class Order {
MenuItem* menus[NUMBER_OF_MENUS];
};
So it's a design decision. And might also depend on the implementation language. In Java, for example, there is no distinction between both, all object variables are references.
Upvotes: 2