区分委托、组合和聚合(Java OO Design)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1384426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:26:11  来源:igfitidea点击:

Distinguishing between delegation, composition and aggregation (Java OO Design)

javaoopaggregationcompositiondelegation

提问by denchr

I am facing a continuing problem distinguishing delegation, composition and aggregation from each other, and identifying the cases where it's the best to use one over the other.

我面临着一个持续的问题,即区分委托、组合和聚合,并确定最好使用一种而不是另一种的情况。

I have consulted a Java OO Analysis and Design book, but my confusion still remains. The main explanation is this:

我查阅了一本 Java OO 分析和设计书,但我的困惑仍然存在。主要的解释是这样的:

Delegation: When my object uses another object's functionality as is without changing it.

委托:当我的对象按原样使用另一个对象的功能而不更改它时。

Composition: My object consists of other objects which in turn cannot exist after my object is destroyed-garbage collected.

组成:我的对象由其他对象组成,这些对象在我的对象被销毁 - 垃圾收集后又不存在。

Aggregation: My object consists of other objects which can live even after my object is destroyed.

聚合:我的对象由其他对象组成,这些对象即使在我的对象被销毁后仍然可以存活。

Is it possible to have a few simple examples demonstrating each case, and the reasoning behind them? How else can these examples be demonstrated other than my object simply having a reference to another object(s)?

是否有可能用几个简单的例子来说明每个案例,以及它们背后的推理?除了我的对象简单地引用另一个对象之外,还能如何演示这些示例?

采纳答案by ChssPly76

Your object would reference another object(s) in all three cases. The difference lies in behavior and / or lifecycle of referenced objects. Some examples:

在所有三种情况下,您的对象都会引用另一个对象。区别在于引用对象的行为和/或生命周期。一些例子:

  1. Composition: House contains one or more rooms. Room's lifetime is controlled by House as Room will not exist without House.

  2. Aggregation: Toy house built from blocks. You can disassemble it but blocks will remain.

  3. Delegation: Your boss asked you to get him a coffee, you've had an intern do it for you instead. Delegation is not a type of association (like composition / aggregation are). The latter two have been discussed on Stack Overflow many times

  1. 组成:房子包含一个或多个房间。Room 的生命周期由 House 控制,因为没有 House 就没有 Room。

  2. 聚合:用积木建造的玩具屋。您可以拆卸它,但块将保留。

  3. 代表团:你的老板让你请他喝咖啡,你让实习生代你做。委托不是一种关联(就像组合/聚合一样)。后两者在 Stack Overflow 上已经讨论过很多次了

In the comment you ask how the implementation would differ in each case, observing that in all cases we invoke methods on the releated objects. It's true that in each case we would have code such as

在评论中,您询问每种情况下的实现有何不同,观察到在所有情况下我们都会调用相关对象上的方法。确实,在每种情况下我们都会有这样的代码

myRoom.doWork();

myBlock.doWork();

myMinion.doWork();

but the differences lie in the life-cycle and cardinality of the related objects.

但区别在于相关对象的生命周期和基数。

For the Component, the Rooms come into existence when the House is created. So we might create them in the constructor of the House.

对于组件,房间在创建房子时就存在了。所以我们可以在 House 的构造函数中创建它们。

In the case of Association (I'll use Tyre and Car) Cars might add Tyres in their constructor, but later you may want to remove and change tyres. So you also have methods such as

在协会的情况下(我将使用轮胎和汽车)汽车可能会在其构造函数中添加轮胎,但稍后您可能想要移除和更换轮胎。所以你也有方法,比如

 removeTyre(FrontLeft)
 addNewTyre(aTyre, BackRight)

And it's quite likely that the aTyre object came from a Factory - we didn't newit in any of the Car's methods.

而且很可能 aTyre 对象来自工厂——我们没有new在任何 Car 的方法中使用它。

In the case of Delegation, you might not even have a member variable to hold the delegate

在委托的情况下,您甚至可能没有成员变量来保存委托

 resourcingPool().getIntern().getCoffee(SkinnyLatte, workstation 7);

the relationship between the objects lasts only as long as the intern is fetching the coffee. Then it returns to the resource pool.

对象之间的关系只在实习生取咖啡时持续。然后它返回到资源池。

回答by NawaMan

Your book explains quite good so let me elaborate and provide you some examples.

你的书解释得很好,所以让我详细说明并为你提供一些例子。

delegation:When my object uses another object's functionality as is without changing it.

委托:当我的对象按原样使用另一个对象的功能而不更改它时。

Sometime a class may logically need to be big. But big class is not a good coding pratice. Also sometime, some functionalities of a class may be implementable in more than one way and you may want to change that some time.

有时,一个类在逻辑上可能需要很大。但是大班不是一个好的编码实践。有时,类的某些功能可能以不止一种方式实现,您可能希望在一段时间内进行更改。


class FeatureHolder {
 void feature() {
  // Big implementation of the feature that you dont want to put in the class Big
 }
}

class Big {
 private FeatureHolder FH = new FeatureHolder();

 void feature() {
  // Delegate to FeatureHolder.
  FH.feature();
 }

 //.. Other features
}

From the above example, Big.feature() call feature of FH as is without changing it. This way, the class Big does not need to contain the implementation of the feature (separation of labour). Also, feature() can implement differently by other class like "NewFeatureHolder" and Big may choose to use the new feature holder instead.

从上面的例子中,Big.feature() 调用 FH 的功能,没有改变它。这样,Big 类就不需要包含特性的实现(分工)。此外,feature() 可以由其他类(如“NewFeatureHolder”)以不同方式实现,Big 可能会选择使用新功能持有者。

composition:My object consists of other objects which in turn cannot exist after my object is destryed-garbage collected.

组合:我的对象由其他对象组成,而这些对象在我的对象被 destryed-garbage 收集后又不存在。

aggregation:My object consists of other objects which can live even after my object is destroyed.

聚合:我的对象由其他对象组成,这些对象即使在我的对象被销毁后仍然可以存活。

Technially, Composition is "part of" and Aggregation is "refer to" relationship. Your arms are part of you. If you no longer live, your arm will die too. Your cloth is not part of you but you have them; as you can guest, your cloth does not go with you.

从技术上讲,组合是“一部分”,而聚合是“参考”关系。你的手臂是你的一部分。如果你不再活着,你的手臂也会死亡。你的衣服不是你的一部分,但你拥有它们;正如你可以做客,你的衣服不会随身携带。

In programming, some objects are part of another object and they have no logical meaning without it. For example, a button is composed into a window frame. If a frame is closed, the button has no reason to be around anymore (Composition). A button may have reference to a database (like to refreash data); when the button is eliminated, the database may still be around (Aggregation).

在编程中,一些对象是另一个对象的一部分,没有它就没有逻辑意义。例如,一个按钮被组合成一个窗口框架。如果一个框架被关闭,按钮就没有理由再存在(组合)。一个按钮可能会引用一个数据库(比如刷新数据);当按钮被消除时,数据库可能仍然存在(聚合)。

Sorry for my English, Hope this helps

对不起我的英语,希望这有帮助

回答by Dave Jarvis

Delegation

代表团

public class A {
  private B b = new B();

  public void methodA() {
    b.methodB();
  }
}

When clients of Acall methodA, class Adelegatesthe call to B's methodB.

当客户A调用时methodA,类A调用委托B's methodB

Rationale.Class A exposes behaviours that belong elsewhere. This can happen in single-inheritance languages where class A inherits from one class, but its clients need behaviours that are implemented in a different class. Further study.

基本原理。A 类公开属于其他地方的行为。这可能发生在单继承语言中,其中类 A 从一个类继承,但其客户端需要在不同类中实现的行为。进一步研究

Hybrid Delegation

混合委托

public class A {
  private B b = new B();

  public void methodA() {
    b.methodB( this );
  }
}

The difference between delegation that involves simple forwarding and delegation that acts as a substitute for inheritance is that the callee must accept a parameter of the caller, exemplified as:

涉及简单转发的委托与替代继承的委托之间的区别在于,被调用者必须接受调用者的参数,例如:

    b.methodB( this );

Rationale.Allows class Binstances to use functionality available from class A, just as class Bwould if it inherited from class A--but without inheritance. Further study.

基本原理。允许类B实例使用 class 可用的功能A,就像 classB从 class 继承A一样——但没有继承。进一步研究

Composition

作品

public class A {
  private B b = new B();

  public A() {
  }
}

Once no more references to a particular instance of class Aexist, its instance of class Bis destroyed.

一旦不再A存在对特定类实例的引用,它的类实例B就会被销毁。

Rationale.Allows classes to define behaviours and attributes in a modular fashion. Further study.

基本原理。允许类以模块化方式定义行为和属性。进一步研究

Aggregation

聚合

public class A {
  private B b;

  public A( B b ) {
    this.b = b;
  }
}

public class C {
  private B b = new B();

  public C() {
    A a = new A( this.b );
  }
}

Once there are no more references to a particular instance of class A, its instance of class Bwill not be destroyed. In this example, both Aand Cmust be garbage collected before Bwill be destroyed.

一旦不再有对 class 的特定实例的引用A,它的 class 实例B将不会被销毁。在这个例子中,AC必须在B被销毁之前被垃圾回收。

Rationale.Allows instances to reuse objects. Further study.

基本原理。允许实例重用对象。进一步研究

Demonstration Without References

没有参考的演示

The names given to these simple patterns are defined by their referential relationships.

这些简单模式的名称由它们的引用关系定义。

回答by Vishwamithra

1) Delegation: Man-driver-car example. A Man bought a car. But that man does not know to drive the car. So he will appoint a driver who knows driving a car. So the Man class wants to perform a transportation using car. But it does not have the interacting- functionality/compatibility with car. So he uses a class which has compatibility with car that is driver which is compatible with man class. Assuming that driver can understand what man says

1) 委托:人-司机-车的例子。一个人买了一辆车。但是那个人不知道开车。所以他会指定一个会开车的司机。所以 Man 类想要使用汽车进行运输。但它不具有与汽车的交互功能/兼容性。所以他使用了一个与 car 兼容的类,即 driver 与 man 类兼容。假设司机能听懂男人说的话

2) Composition: Car simulation is a routine example. To make a car move, wheel rotates. Car class using wheel class rotate functinality as part of its move function, where as wheel is part of car.

2)组成:汽车模拟是一个例行的例子。为了使汽车移动,车轮旋转。使用车轮类的汽车类将旋转功能作为其移动功能的一部分,而车轮是汽车的一部分。

3) Aggregation: Car and its colour. Car class object ferrari will have a colour class object red. But colour class object red can be there as individual class, when user search happens with a specification of red colour.

3) 聚合:汽车及其颜色。汽车类对象法拉利将有一个颜色类对象红色。但是当用户搜索指定红色时,颜色类对象红色可以作为单独的类存在。

回答by Alireza Rahmani Khalili

In a very simple sentence I can say:

用一个非常简单的句子我可以说:

Delegation is:delegate behaviour to other class when you do not want to change it. by change I mean during run time. for example you delegate driver to car class that driver wont change while driving.

委托是:当您不想更改它时,将行为委托给其他类。我的意思是在运行时更改。例如,您将司机委派给司机在驾驶时不会改变的汽车类别。

Composition is:when you want to use behaviour of family of classes (one or more classes, that implements an interface) that you might change during run time. but you should consider these classes can not exist with out main classes, such as rooms of a hotel. If you remove hotel all rooms of hotel will not exist.

组合是:当您想要使用可能在运行时更改的类家族(一个或多个实现接口的类)的行为时。但是您应该考虑这些类不能在没有主类的情况下存在,例如酒店的房间。如果您删除酒店,酒店的所有房间都将不存在。

Aggregation is:same as composition but classes can exist without main class.

聚合是:与组合相同,但类可以在没有主类的情况下存在。