當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Aggregation和Composition的區別用法及代碼示例

聚合和組合說明了對象之間相互通信時的關係類型,這可以在低級設計中用於說明對象之間的關聯。在本文中,我們將討論 Java 編程語言中聚合和組合之間的差異。

Aggregation

它是一種特殊形式的協會,其中:

  • 它代表Has-A的關係。
  • 它是單向關聯,即one-way 關係。例如,一個係可以有學生,但反之亦然是不可能的,因此本質上是單向的。
  • 在聚合中,兩個條目都可以單獨生存,這意味著結束一個實體不會影響另一個實體。
Example of Aggregation in Java

例子:

Java


// Java program to illustrate the  
// Concept of Aggregation 
  
// Importing required classes 
import java.io.*; 
import java.util.*; 
  
// Class 1 
// Student class 
class Student { 
  
    // Attributes of student 
    String name; 
    int id; 
    String dept; 
  
    // Constructor of student class 
    Student(String name, int id, String dept) 
    { 
  
        // This keyword refers to current instance itself 
        this.name = name; 
        this.id = id; 
        this.dept = dept; 
    } 
} 
  
// Class 2 
// Department class contains list of student objects 
// It is associated with student class through its Objects 
class Department { 
    // Attributes of Department class 
    String name; 
    private List<Student> students; 
    Department(String name, List<Student> students) 
    { 
        // this keyword refers to current instance itself 
        this.name = name; 
        this.students = students; 
    } 
  
    // Method of Department class 
    public List<Student> getStudents() 
    { 
        // Returning list of user defined type 
        // Student type 
        return students; 
    } 
} 
  
// Class 3 
// Institute class contains list of Department 
// Objects. It is associated with Department 
// class through its Objects 
class Institute { 
  
    // Attributes of Institute 
    String instituteName; 
    private List<Department> departments; 
  
    // Constructor of institute class 
    Institute(String instituteName,List<Department> departments) 
    { 
        // This keyword refers to current instance itself 
        this.instituteName = instituteName; 
        this.departments = departments; 
    } 
  
    // Method of Institute class 
    // Counting total students of all departments 
    // in a given institute 
    public int getTotalStudentsInInstitute() 
    { 
        int noOfStudents = 0; 
        List<Student> students; 
  
        for (Department dept : departments) { 
            students = dept.getStudents(); 
  
            for (Student s : students) { 
                noOfStudents++; 
            } 
        } 
  
        return noOfStudents; 
    } 
} 
  
// Class 4 
// main class 
class GFG { 
  
    // main driver method 
    public static void main(String[] args) 
    { 
        // Creating object of Student class inside main() 
        Student s1 = new Student("Mia", 1, "CSE"); 
        Student s2 = new Student("Priya", 2, "CSE"); 
        Student s3 = new Student("John", 1, "EE"); 
        Student s4 = new Student("Rahul", 2, "EE"); 
  
        // Creating a List of CSE Students 
        List<Student> cse_students = new ArrayList<Student>(); 
  
        // Adding CSE students 
        cse_students.add(s1); 
        cse_students.add(s2); 
  
        // Creating a List of EE Students 
        List<Student> ee_students 
            = new ArrayList<Student>(); 
  
        // Adding EE students 
        ee_students.add(s3); 
        ee_students.add(s4); 
  
        // Creating objects of EE and CSE class inside 
        // main() 
        Department CSE = new Department("CSE", cse_students); 
        Department EE = new Department("EE", ee_students); 
  
        List<Department> departments = new ArrayList<Department>(); 
        departments.add(CSE); 
        departments.add(EE); 
  
        // Lastly creating an instance of Institute 
        Institute institute = new Institute("BITS", departments); 
  
        // Display message for better readability 
        System.out.print("Total students in institute: "); 
  
        // Calling method to get total number of students 
        // in institute and printing on console 
        System.out.print(institute.getTotalStudentsInInstitute()); 
    } 
} 

輸出:

Total students in institute: 4

輸出說明:在這個例子中,有一個研究所,有許多部門,如 CSE 和 EE。每個部門都沒有。學生的。因此,我們創建一個 Institute 類,它具有或不具有 Object 的引用。 Department 類的對象(即對象列表)。這意味著 Institute 類通過其對象與 Department 類關聯。 Department 類還引用了 Student 類的對象或對象(即對象列表),這意味著它通過其對象與 Student 類關聯。它代表Has-A 關係。在上麵的例子中:學生Has-A姓名。學生Has-A ID。學生 Has-A 部門 部門 Has-A 學生如以下媒體所示。

我們什麽時候使用聚合?

代碼重用最好通過聚合來實現。

作品

組合是聚合的一種受限形式,其中兩個實體彼此高度依賴。

  • 它代表part-of關係。
  • 在組合中,兩個實體相互依賴。
  • 當兩個實體之間存在組合時,組合對象不能離開另一個實體而存在。

例子:

Java


// Java program to illustrate 
// the concept of Composition 
  
// Importing required classes 
import java.io.*; 
import java.util.*; 
  
// Class 1 
// Book 
class Book { 
  
    // Attributes of book 
    public String title; 
    public String author; 
  
    // Constructor of Book class 
    Book(String title, String author) 
    { 
  
        // This keyword refers to current instance itself 
        this.title = title; 
        this.author = author; 
    } 
} 
  
// Class 2 
class Library { 
  
    // Reference to refer to list of books 
    private final List<Book> books; 
  
    // Library class contains list of books 
    Library(List<Book> books) 
    { 
  
        // Referring to same book as 
        // this keyword refers to same instance itself 
        this.books = books; 
    } 
  
    // Method 
    // To get total number of books in library 
    public List<Book> getTotalBooksInLibrary() 
    { 
  
        return books; 
    } 
} 
  
// Class 3 
// Main class 
class GFG { 
  
    // Main driver method 
    public static void main(String[] args) 
    { 
  
        // Creating objects of Book class inside main() 
        // method Custom inputs 
        Book b1 
            = new Book("EffectiveJ Java", "Joshua Bloch"); 
        Book b2 
            = new Book("Thinking in Java", "Bruce Eckel"); 
        Book b3 = new Book("Java: The Complete Reference", 
                        "Herbert Schildt"); 
  
        // Creating the list which contains number of books 
        List<Book> books = new ArrayList<Book>(); 
  
        // Adding books 
        // using add() method 
        books.add(b1); 
        books.add(b2); 
        books.add(b3); 
  
        Library library = new Library(books); 
  
        // Calling method to get total books in library 
        // and storing it in list of user0defined type - 
        // Books 
        List<Book> bks = library.getTotalBooksInLibrary(); 
  
        // Iterating over books using for each loop 
        for (Book bk : bks) { 
  
            // Printing the title and author name of book on 
            // console 
            System.out.println("Title : " + bk.title 
                            + " and "
                            + " Author : " + bk.author); 
        } 
    } 
}

輸出:

Title : EffectiveJ Java and  Author : Joshua Bloch
Title : Thinking in Java and  Author : Bruce Eckel
Title : Java: The Complete Reference and  Author : Herbert Schildt

輸出說明:在上麵的示例中, Library 可以擁有許多相同或不同主題的書籍。因此,如果 Library 被摧毀,那麽該特定 Library 內的所有書籍都將被摧毀。也就是說,如果沒有 Library ,書籍就不可能存在。這就是為什麽它是組合。書是Part-of Library 。

Difference Between Aggregation and Composition in Java

聚合

作品

聚合可以說明為“Has-a”關係,表示對象之間的關聯。 組合意味著一個對象包含在另一個對象中。它是一種特殊類型的聚合(即Has-a關係),這意味著一個對象是另一個對象的所有者,這可以稱為所有權關聯。
對象之間存在相互依賴關係。 存在單向關係,這也稱為“part of”關係。
它是弱類型關聯,兩個對象都有自己獨立的生命周期。 它是強類型的關聯(聚合),子對象沒有自己的生命周期。
關聯對象可以獨立存在並有自己的生命周期。 孩子的生活取決於父母的生活。隻有父對象有獨立的生命周期。
白菱形的 UML 表示表示聚合。 Black Diamond 的 UML 表示表示組合。
例如,學生和部門之間的關係。學生可能沒有院係而存在。 例如,一個文件包含在一個文件夾中,如果刪除該文件夾,裏麵的所有文件都會被刪除。如果沒有文件夾,文件就不能存在。


相關用法


注:本文由純淨天空篩選整理自thejavamentor大神的英文原創作品 Difference Between Aggregation and Composition in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。