关联(association)
如果几个类元的实例之间有联系,那么这几个类元之间的语义关系即关联。关联描述了系统中对象或实例之间的离散连接。关联将一个含有两个或多个有序表的类元,在允许复制的情况下连接起来。最普通的关联是一对类元之间的二元关联。关联的实例之一是链。每个链由一组对象(一个有序列表)构成,每个对象来自于相应的类。二元链包含一对对象。
关联带有系统中各个对象之间关系的信息。当系统执行时,对象之间的连接被建立和销毁。关联关系是整个系统中使用的“胶粘剂”,如果没有它,那么只剩下不能一起工作的孤立的类。
在关联中如果同一个类出现不止一次,那么一个单独的对象就可以与自己关联。如果同一个类在一个关联中出现两次,那么两个实例就不必是同一个对象,通常的情况都如此。
二元关联用一条连接两个类的连线表示。
聚集表示部分与整体关系的关联,它用端点带有空菱形的线段表示,空菱形与聚集类相连接。组成是更强形式的关联,整体有管理部分的特有的职责,它用一个实菱形物附在组成端表示。每个表示部分的类与表示整体的类之间有单独的关联,但是为了方便起见,连线结合在一起,现在整组关联就像一棵树。
依赖(dependency)
两个元素之间的一种关系,其中一个元素(服务者)的变化将影响另一个元素(客户),或向它(客户) 提供所需信息。它是一种组成不同模型关系的简便方法。
依赖表示两个或多个模型元素之间语义上的关系。它只将模型元素本身连接起来而不需要用一组实例来表达它的意思。它表示了这样一种情形,提供者的某些变化会要求或指示依赖关系中客户的变化。
根据这个定义,关联和泛化都是依赖关系,但是它们有更特别的语义,故它们有自己的名字和详细的语义。我们通常用依赖这个词来指其他的关系。
依赖用一个从客户指向提供者的虚箭头表示,用一个构造型的关键字来区分它的种类。
关联(association)和依赖(dependency)的区别:
依赖是比关联弱的关系,关联代表一种结构化的关系,体现在生成的代码中,以java为例:
若类Person单向关联指向类Car ,则在类Person中存在一个属性Car car。
若类Person依赖类Car ,则不会有这个属性,类Car 的实例可能存在于某个方法调用的参数中,或某个方法的局部变量中。
关联(Association Relationship)的代码为:
Public class Person{
Car car=new Car();
}
依赖(Dependency Relationship)的代码为:
Public class Person{
Public void buy(Car car){
}
}
从以上得知关联的主要目的是要得知外部对象的属性和方法,而依赖的主要目的是将对象或类信息作为外部状态传进类中形成外蕴。
在java中关联关系是通过实例变量而实现的,同时关联可以是双向的,关联可以有一对多的关系。
依赖在java语言中体现为局部变量、方法参数,以及对静态的方法调用。依赖总是单向的。
Dependency Relationship
Draw a dependency relationship between two classes, or between a class and an interface, to show that the client class depends on the supplier class/interface to provide certain services, such as:
The client class accesses a value (constant or variable) defined in the supplier class/interface.
Operations of the client class invoke operations of the supplier class/interface.
Operations of the client class have signatures whose return class or arguments are instances of the supplier class/interface.
A dependency relationship is a dotted line with an arrowhead at one end:The arrowhead points to the supplier class.
Association Relationship
An association provides a pathway for communication. The communication can be between use cases and actors, between two classes or between a class and an interface. Associations are the most general of all relationships and consequentially the most semantically weak. If two objects are usually considered independently, the relationship is an association.