问题
I want to understand the difference between composition and aggregation relationship.
Does anyone know a site that explains the UML class diagrams for all relationships?
回答1:
Composition and aggregation have to do with cascading delete behavior.
Do the child objects have a life of their own beyond the parent? If yes, you need aggregation.
If the parent is deleted, do the children need to be deleted as well? If yes, you need composition.
So let's say you have a model where there's a School class, a Building class, and a Student class. A School has a one-to-many relationship with Building and a one-to-many relationship with Student.
The School-to-Building relationship is an example of composition. If you close the School, you might decide to bulldoze the buildings.
The School-to-Student relationship is aggregation. If you close the school, you certainly won't decide to murder all the Students.
You can read what Uncle Bob Martin has to say about it here.
回答2:
The difference lies in the lifetime of the parts of an object.
- If the parts can live independently from the parent, then you have an aggregation.
- If the parts's lifetime are controlled by the parent it is a composition.
The composition can be seen as a special case of an aggregation.
According to The UML User Guide (glossary):
composition: A form of aggregation with strong ownership and coincident lifetime of the parts by the whole
回答3:
Both aggregation and composition represent "has a" relationships. The difference between the two is that composition refers to exclusive ownership. For instance, a transaction "has a" transaction ID number, and that transaction is the only transaction that has that transaction ID number, the ID number is exclusive to the transaction. A transaction also "has a" transaction date, but many transaction might also have that same transaction date. Since the transaction date can be shared among multiple transactions it is not exclusive.
When you are drawing these two relationship types on a UML class diagram a composition relationship would be represented with a filled in diamond where a aggregation relationship would be represented by a diamond which is not filled in.
The book Introduction to Java Programming covers this subject in great detail.
来源:https://stackoverflow.com/questions/4064568/uml-class-diagram-composition-vs-agregation