Difference between dependency and composition?

后端 未结 3 1371
無奈伤痛
無奈伤痛 2021-02-02 00:46

Definitions taken from here

Dependency

Change in structure or behaviour of a class affects the other related class, then there is a dependency b

3条回答
  •  眼角桃花
    2021-02-02 01:26

    Dependency refers to usage of objects only within a functions scope. In other words, instances of the class only exist within the functions (or methods) of the containing class, and are destroyed after functions exit.

    The example you gave for Dependency is not a Dependency because the Employee class contains an instance of an Address, this is called an Aggregation. An aggregation is like a Composition except the object can also exist outside of the class which is using it. (It can be located outside the classes scope). In your example you are passing a copy of an Address to the Employee constructor. But since it is created outside of the Employee object, the Address may also exist else where in the program.

    Just as with Aggregation, Composition is where the component object is available to the entire composite object. This means that all the methods/functions of the composite object can access the component object. The only difference between Aggregation and Composition is that in Composition the component object only exists inside the composite object and no where else in the program. So when the composite object is destroyed, the given component object is also destroyed, and can not exist anywhere else. In your example, The Car is a composite object and the Engine is a component because that instance of the Engine only exists in that particular Car and no where else.

提交回复
热议问题