继承关系(Generalization),又叫泛化
实现关系(Realization)
组合关系(Composition )
聚合关系(Aggregate)
关联关系(Association)
依赖关系(Dependency)
耦合度: 继承>实现>组合>聚合>关联>依赖
在 继承关系 中,子类继承父类的所有功能,父类所具有的属性、方法,子类都应该有。
除了与父类一致的信息,子类中还包括额外的信息。
例如,公交车、出租车都是车
接口(包括抽象类)是方法的集合
在 实现关系 中,类实现了接口,类中的方法实现了接口声明的所有方法。
例如,人、动物都吃饭都睡觉
关联关系 是类与类之间 最常用 的一种关系,表示一类对象与另一类对象之间有联系。
比如说,人有汽车,人有电脑;整体和部分的关系,可以分割,后来形成在一起
public class Person {
private Car car;
}
对于赋值 :
1. 可以在构造方法里赋值
2. 可以通过set方法赋值
Association is a relation between two separate classes which establishes through their Objects.
Association can be
1、one-to-one,
2、one-to-many, i.e. Bank can have many employees
3、many-to-one,
4、many-to-many.
In Object-Oriented programming, an Object communicates to another object to use functionality and services provided by that object.
Composition and Aggregation are the two forms of association.
组合、聚合也属于关联关系,他们3个代码结构一样,只是关联关系的类间关系比其他两种关系要弱。
聚合关系 也表示类之间整体与部分的关系,成员对象是整体对象的一部分,但是成员对象可以脱离整体对象独立存在。
例如,工人和工作服是整体与部分的关系,但是可以分开,没有共同的生命周期。工作服可以穿在别的司机身上,工人也可以换别人的工作服。再比如说,汽车和车轮,电脑和主板。
public class Car {
private Wheel wheel;
}
对于赋值 :
1. 可以在构造方法里赋值
2. 可以通过set方法赋值
It is a special form of Association
where:
1、It represents Has-A’s relationship.
2、It is a unidirectional association i.e. a one-way relationship.
For example, a department can have students but vice versa is not possible and thus unidirectional in nature.
3、In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity.
When do we use Aggregation ?
Code reuse is best achieved by aggregation.
组合关系 表示类之间整体与部分的关系,整体与部分有一致的生存期。一旦整体对象不存在,部分对象也将不存在,整体和部分是同生共死的关系。 皮之不存,毛将焉附
例如,人和脑袋,人和大脑,人和心脏
public class Person {
private Head head;
private Heart heart;
}
对于赋值 :
1. 可以在构造方法里赋值
2. 可以通过set方法赋值
Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.
1、It represents part-of relationship.
2、In composition, both entities are dependent on each other.
3、When there is a composition between two entities, the composed object cannot exist without the other entity.
Aggregation vs Composition
1. Dependency: Aggregation implies a relationship where the child can exist independently of the parent. whereas Composition implies a relationship where the child cannot exist independent of the parent.
2. Type of Relationship: Aggregation relation is “has-a” and composition is “part-of” relation.
3. Type of association: Composition is a strong Association whereas Aggregation is a weak Association.
依赖关系 是一种“使用”关系,当需要表示一个事物使用另一个事物时,使用依赖关系。在大多数情况下,依赖关系体现在某个类的方法使用另一个类的对象作为参数。
例如,汽车依赖汽油,如果没有汽油,则汽车将无法行驶。
public class Car {
public void driveDistance(Oil oil){
...
}
}
对于赋值:
可以在方法中自己创建
可以在方法中传递进来
-----------------------------------------------------------------------------读书笔记摘自 书名:《设计模式就该这样学:基于经典框架源码和真实业务场景》(谭勇德)
-----------------------------------------------------------------------------读书笔记摘自 书名:Article《Association, Composition and Aggregation in Java》