Java中聚合和组合的实现差异 [英] Implementation difference between Aggregation and Composition in Java

查看:441
本文介绍了Java中聚合和组合的实现差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道聚合和组合之间的概念差异。有人可以通过示例告诉我他们之间Java的实现差异吗?

I'm aware of the conceptual differences between Aggregation and Composition. Can someone tell me the implementation difference in Java between them with examples?

推荐答案

构成

final class Car {

  private final Engine engine;

  Car(EngineSpecs specs) {
    engine = new Engine(specs);
  }

  void move() {
    engine.work();
  }
}

汇总

final class Car {

  private Engine engine;

  void setEngine(Engine engine) {
    this.engine = engine;
  }

  void move() {
    if (engine != null)
      engine.work();
  }
}

在组合的情况下,引擎完全封装乘汽车。外界无法获得对引擎的引用。发动机与汽车一起生存和死亡。通过聚合,Car还可以通过引擎执行其功能,但引擎并不总是Car的内部部分。发动机可以互换,甚至完全拆除。不仅如此,外界还可以参考发动机,无论是否在车内,都可以对其进行修补。

In the case of composition, the Engine is completely encapsulated by the Car. There is no way for the outside world to get a reference to the Engine. The Engine lives and dies with the car. With aggregation, the Car also performs its functions through an Engine, but the Engine is not always an internal part of the Car. Engines may be swapped, or even completely removed. Not only that, but the outside world can still have a reference to the Engine, and tinker with it regardless of whether it's in the Car.

这篇关于Java中聚合和组合的实现差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆