java - 依赖和组合之间的区别?

标签 java oop dependencies uml composition

Definitions taken from here

依赖

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.

来自 here 的 Java 中的具体示例和 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();
  }
}

最佳答案

从两个构造函数中可以看出区别:

  • Dependency:Address 对象来自外部,分配在其他地方。这意味着 AddressEmployee 对象分别存在,并且只依赖彼此。

  • Composition:在这里您可以看到在内部 Car 创建了一个新的EngineEngine 对象是 Car 的一部分。这意味着 Car Engine 组成

关于java - 依赖和组合之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21022012/

相关文章:

javascript - Javascript:在请求的对象“未找到”的情况下,使用模式空对象模式,RORO,未定义等作为Get函数的返回参数

php - OOP——我应该开发多少类?

ubuntu - 当我尝试安装 nginx 时未遇到的包

java - 如何从多项式字符串中获取系数和指数?

javax.net.ssl.SSLException : Unrecognized SSL message, 明文连接?

python - 我如何在 python 中以相反的方式实现内置对象和创建的类之间的操作?

java - EJB 容器中的 Spring 2.5

java - 为部署到 heroku tomcat 的 Java Web WAR 找不到添加依赖项的类

Java DOM 解析器 XML

java - 时间戳计算函数