Conversion of Association,Aggregation and composition into code in java?

回眸只為那壹抹淺笑 提交于 2020-01-03 09:02:21

问题


I know There are different way of reprentation for Conversion of Association,Aggregation and composition in java. But when we convert them into code(java classes) they are all represented in same manner. Like Student taught by teacher which is association will be represented with Student class having instance variable of Class Teacher.

Department has professors which is aggregation will be also be represented with Department class having instance variable (array )of Class Professors.

University has departments which is composition will be also be represented with University class having instance variable (array )of Class department.

So all are reprented in same manner in terms of code. So what benefits terms Association,Aggregation and composition provide to developer?


回答1:


You're missing part of the story with Composition. It mandates a couple of extra properties:

  • immutability of the parent (i.e. child can't switch parents)
  • lifecycle responsibility for the children lies with the parent. i.e. the parent is responsible for creating and deleting child instances. Child can't live after parent dies.

You're right that the association will manifest as a reference / collection of references in child & parent respectively. But the code must also enforce the rules above if it's to ensure Composition semantics are enforced.

As for Aggregation: I don't use it. The semantics are too loose and it offers no advantages over straight associations.

hth.



来源:https://stackoverflow.com/questions/7195151/conversion-of-association-aggregation-and-composition-into-code-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!