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

发布于 2024-08-03 12:11:40 字数 348 浏览 5 评论 0原文

我面临着一个持续的问题,如何区分委托、组合和聚合,并确定最好使用其中一种的情况。

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

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

组合:我的对象由其他对象组成,在我的对象被销毁(垃圾收集)后,这些对象将无法存在。

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

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

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:

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)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

爱情眠于流年 2024-08-10 12:11:40

委托

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

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

A 的客户端调用 methodA 时,类 A 将调用委托给 BmethodB

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

混合

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

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

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

    b.methodB( this );

Rationale. 允许类 B< /code> 实例使用类 A 提供的功能,就像类 B 继承自类 A 一样 - 但没有继承。 进一步研究

组合

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

  public A() {
  }
}

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

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

聚合

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 );
  }
}

一旦不再有对类 A 的特定实例的引用,其类 B 的实例将不会被销毁。在此示例中,在销毁 B 之前,必须对 AC 进行垃圾收集。

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

无引用的演示

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

Delegation

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

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

When clients of A call methodA, class A delegates the call to 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.

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 B instances to use functionality available from class A, just as class B would if it inherited from class A--but without inheritance. Further study.

Composition

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

  public A() {
  }
}

Once no more references to a particular instance of class A exist, its instance of class B is destroyed.

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 B will not be destroyed. In this example, both A and C must be garbage collected before B will be destroyed.

Rationale. Allows instances to reuse objects. Further study.

Demonstration Without References

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

流云如水 2024-08-10 12:11:40

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

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

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

  3. 委派:你的老板让你给他倒杯咖啡,你已经让一名实习生为你做这件事了。委托不是一种关联(如组合/聚合)。后两者已在 Stack Overflow 上多次讨论

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

myRoom.doWork();

myBlock.doWork();

myMinion.doWork();

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

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

在关联的情况下(我将使用轮胎和汽车),汽车可能会在其构造函数中添加轮胎,但稍后您可能想要删除和更换轮胎。因此,您还拥有诸如这样的方法

 removeTyre(FrontLeft)
 addNewTyre(aTyre, BackRight)

,并且 aTyre 对象很可能来自工厂 - 我们没有在 Car 的任何方法中 new 它。

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

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

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

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

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.

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 new it in any of the Car's methods.

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.

握住你手 2024-08-10 12:11:40

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

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

有时,一个类在逻辑上可能需要很大。但大类并不是一个好的编码实践。有时,类的某些功能可能可以通过多种方式实现,并且您可能希望在某个时候更改它。


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
}

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

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

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

从技术上讲,组合是“一部分”关系,聚合是“引用”关系。你的手臂是你的一部分。如果你不再活着,你的手臂也会死去。你的衣服不是你的一部分,但你拥有它们;正如您所言,您的衣服并不适合您。

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

抱歉我的英语不好,希望这有帮助

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.

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

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

硪扪都還晓 2024-08-10 12:11:40

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

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

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

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

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.

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.

没有伤那来痛 2024-08-10 12:11:40

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

委托是:当您不想更改行为时将其委托给其他类。我所说的改变是指在运行时。例如,您将驾驶员委派给驾驶员在驾驶时不会更改的汽车类别。

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文