var*_*ava 2 java oop composition aggregation
我正在通过以下链接找出组合和聚合之间的区别。
https://www.geeksforgeeks.org/association-composition-aggregation-java/
我能够理解,组合意味着一种关系,其中孩子不能独立于父母而存在,而聚合意味着一种关系,其中孩子可以独立于父母而存在。但无法理解如何以编程方式区分。下面是链接中给出的聚合和组合的示例。在这两种情况下,除了 Student 和 Department 类有一个额外的变量“name”外,这两种类的结构相同。如在组合中“子不能独立于父而存在”,但是在这里,我可以创建一个单独的 Book 对象并使用它,而无需将其添加到 Library。
聚合
// student class
class Student
{
String name;
int id ;
String dept;
Student(String name, int id, String dept)
{
this.name = name;
this.id = id;
this.dept = dept;
}
}
/* Department class contains list of student
Objects. It is associated with student
class through its Object(s). */
class Department
{
String name;
private List<Student> students;
Department(String name, List<Student> students)
{
this.name = name;
this.students = students;
}
public List<Student> getStudents()
{
return students;
}
}
Run Code Online (Sandbox Code Playgroud)
作品
class Book
{
public String title;
public String author;
Book(String title, String author)
{
this.title = title;
this.author = author;
}
}
// Libary class contains
// list of books.
class Library
{
// reference to refer to list of books.
private final List<Book> books;
Library (List<Book> books)
{
this.books = books;
}
public List<Book> getTotalBooksInLibrary()
{
return books;
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知(也许其他人可以给出更好的答案),您无法仅通过查看 Java 代码来评估这种关系是聚合还是组合。正好相反。
首先,您创建一个世界的概念模型。图书馆有书,汽车有轮子。然后你会想 -在我工作的背景下,没有图书馆的书存在,或者没有汽车的轮子存在有意义吗??因此,例如,如果您正在编写赛车游戏,您将不会使用汽车以外的轮子。但是如果您正在编写一些汽车修理应用程序,您将独立于某些特定汽车处理车轮。
所以首先你要决定是否需要聚合或组合,然后在你的代码中实现它。实现可能是该对象Car具有,List<Wheel>但您无法仅凭此判断它是组合还是聚合。关键是你根据你的概念模型解释代码(实现),然后根据它使用它。
如果是组合,使用上可能会有一些限制:
Car将持有对Wheel.Wheel 甚至可能是私有或包私有类。Car保存在数据库中,当你删除它时,你也会自动删除它Wheel的所有s。但是,如果您决定它的组合,则由您来执行这些限制。