Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
922 views
in Technique[技术] by (71.8m points)

oop - Aggregation vs Composition vs Association vs Direct Association

I am reviewing my knowledge in object-oriented programming. Under the relationship between classes topic, I have encountered some relationships which are a bit ambiguous to me.

I know dependency "uses-a" and inheritance "is-a" but I'm a bit unfamiliar with Aggregation, Composition, Association and Direct Association; also, which of them is "has-a" relationship. Some use Aggregation interchangeably with Association.

What is Direct Association? Also, what is Composition? In UML diagrams, the arrows that represents them are different. I would be really thankful if you could clear these things out for me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please note that there are different interpretations of the "association" definitions. My views below are heavily based on what you would read in Oracle Certification books and study guides.

Temporary association

A usage inside a method, its signature or as a return value. It's not really a reference to a specific object.

Example: I park my Car in a Garage.

Temporary Association UML

Composition association

A so-called "STRONG relationship": The instantiation of the linked object is often hard coded inside the constructor of the object. It cannot be set from outside the object. (Composition cannot be a many-to-many relationship.)

Example: A House is composed of Stones.

Composition UML

Direct association

This is a "WEAK relationships". The objects can live independent and there are usually setters or other ways to inject the dependent objects.

Example: A Car can have Passengers.

Direct Association UML

Aggregation association

Very similar to a Direct association. It's also a "WEAK relationship" with independent objects. However here the associated objects are a crucial part of the containing object.

Example: A Car should have Tires.

Aggregation UML

Note: Both Direct associations and Aggregation associations are often generalized as "Associations". The difference is rather subtle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...