class Book {
private Chapter[] chapters = new Chapter[5];
}
class Chapter {
private Book book;
}
这是实现上述关系的正确方法吗? 我需要对此进行解释。谢谢。
最佳答案
这还不够。
在组合关系中,如果整个
实例被销毁,部分
实例也应该立即被销毁。
你应该有一些代码(一些机制)来做到这一点。
例如,如果您从类外部推送 Chapter
的实例(例如通过使用构造函数),您应该小心地在 Book
实例被删除。
如果您的实例是在 Book
类中创建的(通过 new ...),则无需执行任何操作,您的 Chapter
实例将被删除 Book
实例。
在此引用资料中:Object Prime,第三版(Scott W. Ambler,2004 年)
在(13.4.12.7 实现组合)
As you might have guessed, aggregation and composition associations are handled exactly the same way as associations. The main difference, from a programming point-of-view, is aggregation implies a tighter relationship between the two classes than association does, and composition implies an even tighter relationship still. Although Fig. 13.11 does not include composition associations, the association between Seminar and Course is tight, in fact, at least as tight as you would see with composition (unfortunately the sentence rule does not make sense in this case). In Fig. 13.31, you see the result of this closeness in the implementation of the remove() method in the Course class—when a course is removed, its seminars are also removed. This type of lifecycle management code is typical within composition hierarchies.
/** * Remove a course * * @postcondition The course and its seminars will be removed */ public void remove() { if (getSeminars() != null) { // Clone the original set because we can't safely remove // the items from the set while we iterate over it HashSet set = (HashSet) getSeminars().clone(); Iterator iterator = set.iterator(); // Remove each seminar of this course while (iterator.hasNext()) { Seminar seminar = (Seminar) iterator.next(); // Remove the seminar from the collection getSeminars().remove(seminar); } } // Remove the instance from permanent storage // Persistence code ... }
考虑这个例子:
class Person {
private final Brain brain;
Person(Brain humanBrain) {
brain = humanBrain;
}
}
在代码的其他部分我们可以这样定义:
Brain b = new Brain();
// or we have an instance of Brain in other scopes
// not exactly in this scope
Person p1 = new Person(b);
Person p2 = new Person(b);
因此,在这段代码中,我们可以将 Brain
的一个实例设置为两个不同的 Persons
。
注意:在组合中,我们应该管理实例的生命周期。只定义任何类的private final
,不显示它们之间的Composition。
例如,下面的例子可以是一个组合。因为在删除 whole
时删除了 Part
的实例:
public class House {
private final Room room;
public House() {
room = new Room();
}
}
在作文中:
整体
可能直接负责部分
的创建或销毁。或者它可以使用已经从类外部(由代码的其他部分)创建和管理的“部分”。在这种情况下,part
的删除应该由外部代码管理,part
应该在 whole
删除之后立即删除。
我们应该建立一种机制,在删除whole
的同时删除part
。 如果我们不删除部分
并在其他整体
中使用它,则它是聚合或关联。
关于java - 在 Java 中实现组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48338288/