据作者的个人理解,关系的强度:依赖<关联<聚合<组合。其实这四个名词只是为了描述类之类关系的紧密的程度而做的区分。
In fact, composition was originally called aggregation-by-value in an earlier UML draft, with “normal” aggregation being thought of as aggregation-by-reference.对这句话的理解,我认为聚合只是引用,组合而是去New对象了,赋值了。The distinction between aggregation and composition is more of a design concept and is not usually relevant during analysis. 聚合和组合是在设计时的一种关系说明.
个人理解,如有错误,敬请指正。
------------------- 参考爱的分割线 -------------------
aggregation:聚合关系 composition组合关系
Finally, a word of warning on terminology. While UML uses the terms association, aggregation, andcomposition with specific meanings, some object-oriented authors use one or more of these terms with slightly different interpretations. For example, it is fairly common to see all three UML relationships grouped under a single term, say composition, and then to discuss object-oriented relationships as being either inheritance (generalization) or composition.
——摘自《Java面向对象编程》,作者:孙卫琴
以上关系的耦合度依次增强(关于耦合度的概念将在以后具体讨论,这里可以暂时理解为当一个类发生变更时,对其他类造成的影响程度,影响越小则耦合度越弱,影响越大耦合度越强)。由定义我们已经知道,依赖关系实际上是一种比较弱的关联,聚合是一种比较强的关联,而组合则是一种更强的关联,所以笼统的来区分的话,实际上这四种关系、都是关联关系。
其关系强弱为: 依赖<关联 < 聚合 < 组合
依赖关系比较好区分,它是耦合度最弱的一种,在java中表现为局域变量、方法的形参,或者对静态方法的调用,如下面的例子:Driver类依赖于Car类,Driver的三个方法分别演示了依赖关系的三种不同形式。
class Car {
public static void run(){
System.out.println("汽车在奔跑");
}
}
class Driver {
//使用形参方式发生依赖关系
public void drive1(Car car){
car.run();
}
//使用局部变量发生依赖关系
public void drive2(){
Car car = new Car();
car.run();
}
//使用静态变量发生依赖关系
public void drive3(){
Car.run();
}
} 关联关系在java中一般使用成员变量来实现,有时也用方法形参的形式实现。依然使用Driver和Car的例子,使用方法参数形式可以表示依赖关系,也可以表示关联关系,毕竟我们无法在程序中太准确的表达语义。在本例中,使用成员变量表达这个意思:车是我自己的车,我“拥有”这个车。使用方法参数表达:车不是我的,我只是个司机,别人给我什么车我就开什么车,我使用这个车。
class Driver {
//使用成员变量形式实现关联
Car mycar;
public void drive(){
mycar.run();
}
...
//使用方法参数形式实现关联
public void drive(Car car){
car.run();
}
}
class Driver {
//使用成员变量形式实现聚合关系
Car mycar;
public void drive(){
mycar.run();
}
} 假如给上面代码赋予如下语义:车是一辆私家车,是司机财产的一部分。则相同的代码即表示聚合关系了。聚合关系一般使用setter方法给成员变量赋值。
假如赋予如下语义:车是司机的必须有的财产,要想成为一个司机必须要先有辆车,车要是没了,司机也不想活了。而且司机要是不干司机了,这个车就砸了,别人谁也别想用。那就表示组合关系了。一般来说,为了表示组合关系,常常会使用构造方法来达到初始化的目的,例如上例中,加上一个以Car为参数的构造方法
public Driver(Car car){
mycar = car;
}参考:http://www.jguru.com/faq/view.jsp?EID=51520
http://blog.csdn.net/zhengzhb/article/details/7190158
http://blog.csdn.net/zhy0511/article/details/6544459
原文:http://blog.csdn.net/paincupid/article/details/43341737