关联、聚合和组合有什么区别? [英] What is the difference between association, aggregation and composition?

查看:33
本文介绍了关联、聚合和组合有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关联、聚合和组合有什么区别?请从实现的角度解释一下.

What is the difference between association, aggregation, and composition? Please explain in terms of implementation.

推荐答案

对于两个对象,FooBar 可以定义关系

For two objects, Foo and Bar the relationships can be defined

关联 - 我与一个对象有关联.Foo 使用 Bar

Association - I have a relationship with an object. Foo uses Bar

public class Foo { 
    void Baz(Bar bar) {
    } 
};

组合 - 我拥有一个对象,我对它的生命周期负责.当 Foo 死亡时,Bar

Composition - I own an object and I am responsible for its lifetime. When Foo dies, so does Bar

public class Foo {
    private Bar bar = new Bar(); 
}

聚合 - 我有一个从别人那里借来的对象.当 Foo 死亡时,Bar 可能会继续存在.

Aggregation - I have an object which I've borrowed from someone else. When Foo dies, Bar may live on.

public class Foo { 
    private Bar bar; 
    Foo(Bar bar) { 
       this.bar = bar; 
    }
}

这篇关于关联、聚合和组合有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆