依赖与构成的区别? [英] Difference between dependency and composition?
问题描述
依赖关系
更改类的结构或行为会影响其他相关的
类,那么这两个类之间有依赖关系。它需要
不一样反之亦然。
Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.
组合
组合是聚合的一种特殊情况。在更具体的
方式中,限制聚合被称为组合。当对象
包含另一个对象时,如果包含的对象不存在
,而不存在容器对象,则称为
组合。
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.
Concrete examples in Java from here and here
依赖关系
class Employee {
private Address address;
// constructor
public Employee( Address newAddress ) {
this.address = newAddress;
}
public Address getAddress() {
return this.address;
}
public void setAddress( Address newAddress ) {
this.address = newAddress;
}
}
组合
final class Car {
private final Engine engine;
Car(EngineSpecs specs) {
engine = new Engine(specs);
}
void move() {
engine.work();
}
}
推荐答案
差异可以在两个构造函数中看到:
The difference can be seen in the two constructors:
-
依赖关系:
地址
对象来自外部,它被分配到其他地方。这意味着地址
和Employee
对象单独存在,只有依赖
Dependency: The
Address
object comes from outside, it's allocated somewhere else. This means that theAddress
andEmployee
objects exists separately, and only depend on each other.
组合:在这里你看到一个新的引擎
被创建 Car
。 Engine
对象是 Car
的一部分。这意味着 Car
是 li>
Composition: Here you see that a new Engine
is created inside Car
. The Engine
object is part of the Car
. This means that a Car
is composed of an Engine
.
这篇关于依赖与构成的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!