多谢楼上几位的回复,基本同意各位的见解。仔细想了一下,觉得要写代码,的确变化比较多,这也是我开始为什么想从实现上分析这三种关系的原因。尽管实现方式很多,但我还是写了一种实现的代码,我没有写 把对象做为参数传递的情况,不过下面的代码道理是一样的。
======
组合
======
public class A {
//Constructor function must include B and C, all of them have the same life cycle.
public A() {
B b = new B();
C c = new C();
}
...
}
public class B{
}
public class C{
}
======
聚合
======
public class A {
public A() {
}
/* This method is a must method in class A, but this method is called after the constructor function is finished. So A and B,C have the different life cycle. Class A could exist without B,C*/
public void MethodOfA(){
B b = new B();
C c = new C();
}
public class B{
}
public class C{
}
========
关联
========
public class A {
public A() {
}
/* This method is not a must method in class A
Class A only have association with B C when this method is called
*/
public void Method-need-BC(){
B b = new B();
C c = new C();
}
public class B{
}
public class C{
}