依赖和组合之间的区别?

问题描述 投票:0回答:4

定义取自此处

依赖性

类的结构或行为的变化会影响其他相关类 类,那么这两个类之间存在依赖关系。它需要 不一样,反之亦然。当一个类包含另一个类时 发生这种情况。

成分

组合是聚合的一个特例。在更具体的 方式,受限聚合称为组合。当一个物体 包含另一个对象,如果包含的对象不存在 如果不存在容器对象,则调用 组成。

来自herehere

的Java具体示例

依赖性

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();
  }
}
java oop dependencies uml composition
4个回答
51
投票

可以在两个构造函数中看到差异:

  • 依赖

    Address
    对象来自外部,它被分配在其他地方。这意味着
    Address
    Employee
    对象单独存在,并且仅 依赖 彼此。

  • 组合:在这里您可以看到在

    Engine
    内部创建了一个新的Car
    Engine
    对象是
    Car
    的一部分。这意味着
    Car
    是由
    Engine
    组成
    
    


24
投票

感谢

Marko Topolnik

为此...


当一个对象“依赖”另一个对象时,就会发生

  1. Dependency

    。它可以在两个对象之间有或没有关系的情况下发生。实际上,一个对象甚至可能不知道另一个对象的存在,但它们可能是依赖的。 示例:生产者-消费者问题。生产者不需要知道消费者存在,但它必须执行wait()和notify()。所以,“不”,依赖不是关联的子集。

    
    

  2. Composition

    :是一种关联类型,其中“子”对象不能在没有父类的情况下存在。即,如果子对象存在,那么它必须位于父对象中,而不是其他地方。

    
    
    EG:一辆汽车(母车)有燃油喷射系统(子车)。现在,在汽车外部安装燃油喷射系统是没有意义的(它将毫无用处)。也就是说,没有汽车,燃油喷射系统就不可能存在。

  3. Aggregation

    :这里,子对象可以存在于父对象之外。 汽车有司机。驾驶员可以存在于车外。

    
    


1
投票

您为依赖关系提供的示例

不是

依赖关系,因为 Employee 类包含地址的实例,这称为聚合。聚合类似于组合,只不过对象也可以存在于使用它的类之外。 (它可以位于类范围之外)。 在您的示例中,您将 Address 的副本传递给 Employee 构造函数。但由于它是在 Employee 对象之外创建的,因此 Address 也可能存在于程序中的其他位置。 与聚合一样,组合是组件对象可用于整个复合对象的地方。这意味着复合对象的所有方法/函数都可以访问组件对象。聚合和组合之间的唯一区别是,在组合中,组件对象仅存在于组合对象内部,而不存在于程序中的其他位置。因此,当复合对象被销毁时,给定的组件对象也被销毁,并且不能存在于其他任何地方。在您的示例中,汽车是一个复合对象,引擎是一个组件,因为引擎的实例仅存在于该特定汽车中,而不存在于其他地方。


0
投票

但是,可以在不构成组合的情况下进行依赖注入。

定义

简单来说,依赖注入就是向封装代码块(例如类、函数、块等)添加参数,而不是使用没有参数的文字过程代码。

组合是指在实例化正在组合的对象时使用依赖项注入的参数/参数

组合的依赖注入

Syringe 类由 Drug 组成,因为 Syringe 将 drug 保存为成员变量。 (可以想象,注射器可能由多个依赖项组成,而不仅仅是单一药物依赖项,但即使是这种单依赖项组合的退化情况仍然是组合。)

Class Drug def __init__(name) @drug = name end def contents return @drug end end Class Syringe def __init__(drug) @drug = drug end def inject() payload = @drug #save the value to return @drug = nil #clear loaded drug return payload end end amoxicillin = Drug.new('amoxicillin') #these two lines are the key difference. compare them with the 'same' lines in the other other example syringe = Syringe.new(amoxicillin) syringe.inject()

无组合的依赖注入

将此与存在依赖注入但不构成组合的情况进行对比: 关键区别在于注入的依赖项不会“组成”Syringe 类,即保存为 Syringe 对象的实例变量

Class Drug def __init__(name) @drug = name end def contents return @drug end end Class Syringe def inject(drug) return drug.contents end end amoxicillin = Drug.new('amoxicillin') #these two lines are the key difference. compare them with the 'same' lines in the other other example syringe = Syringe.new() syringe.inject(amoxicillin)

© www.soinside.com 2019 - 2024. All rights reserved.