其关系强弱为 关联<聚合<组合
关联:在程序中相当于把已经实例化的对象A做为另一对象B方法的参数传递引用。
组合:即为内部类
聚合:其做法介于两者之间。不过我更觉得聚合相当于一个在外部已经申明的A,然后把A放在B中做为一个变量使用。
不知我理解的是不是正确,请大家从 实现 的角度发表一下意见吧。
其关系强弱为 关联<聚合<组合
关联:在程序中相当于把已经实例化的对象A做为另一对象B方法的参数传递引用。
组合:即为内部类
聚合:其做法介于两者之间。不过我更觉得聚合相当于一个在外部已经申明的A,然后把A放在B中做为一个变量使用。
不知我理解的是不是正确,请大家从 实现 的角度发表一下意见吧。
1的那个要有一个collection储存多的那个
你说的只是聚合中的一种情况而已。
象组合的实现:内部类。 一个类里面也可以有多个内部类,这同样是一对多的关系。
组合就是一种很强烈的关联,必须在被组合对象生成的时候,组合对象也就必须生成了
像这样
|
因为内部类如果不是静态申明的话,必须被实例化后才能得到内部类对象。所以内部类可以与包容它的外部类有不同的生命周期。
其实我也只是想从实现的角度去认识 这三种强弱关系的不同。
CC,概念容易理解,你说的没错“组合就是一种很强烈的关联,必须在被组合对象生成的时候,组合对象也就必须生成了”,“组合”例子的代码
容易实现, 但“聚合”,“关联”的代码如何写才能区别出三者强弱关系呢?
请各位道友写几笔示意代码,让大家看看。
======
组合
======
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{
}
Association:
Uses the services of another class
Aggregation:
A class “owns” another class
Composition:
A class is composed of another class; refers to an aggregation within which the component parts and the larger encompassing whole share a lifetime