简体   繁体   中英

Composition vs. Aggregation: Ownership of the contained object being reused in other containing objects

I was reading a post Inheritance and Composition (Is-a vs Has-a relationship) in Java and I ambit confused by what this following statement.

It's also worth noting that in this case, the containing Computer object has ownership of the contained objects if and only if the objects can't be reused within another Computer object. If they can, we'd be using aggregation, rather than composition, where ownership isn't implied.

Here is the code snippet being referenced

public class Computer{
    private Processor processor;
    private Memory memory;
    private SoundCard soundCard;
    //... more code
}

What does it mean by being reused within another Computer object ? Does it mean that when I have two instantiations of Computer that they shouldn't be sharing those composed objects (processor, memory, soundcard)?

Can someone give an example where aggregation is used instead of composition following the statement above?

The question is, how are the private fields instantiated?

Does it mean that when I have two instantiations of Computer that they shouldn't be sharing those composed objects...

Yes.

If a Computer object instantiates its own Processor so that no other object has a reference to that Processor instance, then it "has ownership of" its Processor , which the quote refers to as aggregation .

Contrast that scenario with a Computer object that receives its Processor through a getter method or constructor argument. In this case, the Processor is instantiated by some other object, and the Computer does not have sole ownership of its Processor , because it does not have the only reference to the Processor object. The quote refers to this relationship as composition .

In practice, the difference between aggregation and composition rarely matters. The difference between composition and inheritance is far more important.

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