简体   繁体   中英

Does combining composition with association still follow the rules of OOP?

When it comes to class diagrams, can an association or aggregation exist between two objects that are in composition with one base object?

Example: Class Car has a composition relation with class Engine and class Fueltank . So Car has An Engine and a Fueltank , and Engine and a Fueltank are dependent on Car . But Engine also needs information from Fueltank , without intervention of Car (in accordance with a sequence diagram for example). That means Engine and Fueltank also have a relationship although, they're both compositions of the Car . See diagram below:

在此处输入图像描述

So, the question is, may such “loops”, or better redudant associations, in class diagrams occur? Or does that undermine the rules of OOP?

This is legal UML...

This kind of combination of composition and association is perfectly legal in UML and does not undermine OOP. There are only a few constraints in UML in this regard:

  • Composite aggregation is a strong form of aggregation that requires a part object be included in at most one composite object at a time.

  • Compositions may be linked in a directed acyclic graph with transitive deletion characteristics;

  • An end Property of an Association may only be marked as a shared or composite aggregation if the Association is binary and the other end is not marked as a shared or composite aggregation.

The first two restrictions are at object level and not necessarily at the class. The last restriction is for the class diagram: it says that a same association can't have composite or shared aggregation at both end. None of those restrictions are relevant for your diagram.

... but may not express what you think

The problem is that this diagram does not express what you think. It says that a Car c is composed of an Engine e and a Fueltank f ; it also says that e is aggregated with a Fueltank, which could be f by coincidence, but which could also be another Fueltank and even a Fueltank of another Car . The model does not well represent the triangular relationship between the classes. Here some hints:

  • You may prevent the inconsistencies by adding some constraints that the engine fuel tank is the same than the car fuel tank.
  • You may make the engine/fueltank relation a derived association (ie somehow the engine's fuel tank will be derived from the car's fuel tank.
  • You may make the car/fueltank relation a derived association (ie the car's fuel tank is derived from its engine).
  • you ignore the relationship engine/fueltank and instead, use the car as a mediator between its components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM