依赖
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.
依赖
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();
}
}
最佳答案
从两个构造函数中可以看出区别:
Dependency:
Address
对象来自外部,分配在其他地方。这意味着Address
和Employee
对象分别存在,并且只依赖彼此。Composition:在这里您可以看到在内部
Car
创建了一个新的Engine
。Engine
对象是Car
的一部分。这意味着Car
由Engine
组成。
关于java - 依赖和组合之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21022012/