[翻译]Java中的关联,组合和聚合(Association, Composition and Aggregation in Java)

前言:

这是一篇关于Java中关联,组合和聚合的翻译,原文地址在这里。我会一段一段地给出原文,然后在下面给出翻译,翻译这篇文章,旨在学习交流。翻译中出现的图片和代码,都直接从原文引用,版权归原文作者所有。

我个人觉得,原文中关于组合(Composition )的例子:图书馆和书,举得并不准确,这应该是一个聚合的例子。但其对关联、组合、聚合含意的描述也有些独到的见解。兼听则明,偏信则暗,尽信书不如无书,其中正误还需读者明查。


原文:

Association

Association is relation between two separate classes which establishes through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many.
In Object-Oriented programming, an Object communicates to other Object to use functionality and services provided by that object. Composition and Aggregation are the two forms of association.

译文:

关联

关联是两个独立的类之间,通过它们的对象建立的关系。关联可以是一对一,一对多,多对一,多对多。
在面向对象编程中,一个对象使用其他对象提供的方法和服务与它通信。组合和聚合是两种形式的关联。

Associatn.png
// Java program to illustrate the 
// concept of Association 
import java.io.*; 

// class bank 
class Bank 
{ 
    private String name; 
    
    // bank name 
    Bank(String name) 
    { 
        this.name = name; 
    } 
    
    public String getBankName() 
    { 
        return this.name; 
    } 
} 

// employee class 
class Employee 
{ 
    private String name; 
    
    // employee name 
    Employee(String name) 
    { 
        this.name = name; 
    } 
    
    public String getEmployeeName() 
    { 
        return this.name; 
    } 
} 

// Association between both the 
// classes in main method 
class Association 
{ 
    public static void main (String[] args) 
    { 
        Bank bank = new Bank("Axis"); 
        Employee emp = new Employee("Neha"); 
        
        System.out.println(emp.getEmployeeName() + 
            " is employee of " + bank.getBankName()); 
    } 
} 

原文:

Output:

译文:

输出:

Neha is employee of Axis

原文:

In above example two separate classes Bank and Employee are associated through their Objects. Bank can have many employees, So it is a one-to-many relationship.

译文:

在上面的例子中,两个独立的类BankEmployee 通过它们的对象关联。银行有很多顾员,因此是一个一对多的关系。

Aggre.png

原文:

Aggregation

It is a special form of Association where:

  • It represents Has-A relationship.
  • It is a unidirectional association i.e. a one way relationship. For example, department can have students but vice versa is not possible and thus unidirectional in nature.
  • In Aggregation, both the entries can survive individually which means ending one entity will not effect the other entity

译文:

聚合

它是一个特殊的关联:

  • 它代表‘has-a’(有一个)关系。
  • 它是一个单向的关联,例如:一种单方面的关系. 举个例子: 院系可以有多个学生,但反过来就不可能(译注:学生不可能有多个学院),这本质上是单向关联.
  • 在聚合中,两个类的实例可以单独存活,这意味着,结束一个实例不会影响其他实例.
// Java program to illustrate 
//the concept of Aggregation. 
import java.io.*; 
import java.util.*; 
  
// 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; 
    } 
} 
  
/* Institute class contains list of Department 
Objects. It is asoociated with Department 
class through its Object(s).*/
class Institute  
{ 
      
    String instituteName; 
    private List<Department> departments; 
      
    Institute(String instituteName, List<Department> departments) 
    { 
        this.instituteName = instituteName; 
        this.departments = departments; 
    } 
      
    // count 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; 
    } 
      
}  
  
// main method 
class GFG 
{ 
    public static void main (String[] args)  
    { 
        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"); 
      
        // making a List of  
        // CSE Students. 
        List <Student> cse_students = new ArrayList<Student>(); 
        cse_students.add(s1); 
        cse_students.add(s2); 
          
        // making a List of  
        // EE Students 
        List <Student> ee_students = new ArrayList<Student>(); 
        ee_students.add(s3); 
        ee_students.add(s4); 
          
        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); 
          
        // creating an instance of Institute. 
        Institute institute = new Institute("BITS", departments); 
          
        System.out.print("Total students in institute: "); 
        System.out.print(institute.getTotalStudentsInInstitute()); 
    } 
} 

原文:

Output:

译文:

输出:

Total students in institute: 4

原文:

In this example, there is an Institute which has no. of departments like CSE, EE. Every department has no. of students. So, we make a Institute class which has a reference to Object or no. of Objects (i.e. List of Objects) of the Department class. That means Institute class is associated with Department class through its Object(s). And Department class has also a reference to Object or Objects (i.e. List of Objects) of Student class means it is associated with Student class through its Object(s).
It represents a Has-A relationship.

译文:

在这个例子中,一个学院有若干院系,像CSE,EE。每一个院系有若干学生。因此,我们创建了Institute(学院)类,它有指向单个Department(院系)对象或一系列Department(院系)对象(例如对象列表)的一个引用。这意味着,Institute(学院)类通过Department院系类的对像与院系类关联。并且院系类还引用Student(学生类)的一个或多个对象(例如对象列表),意味着它通过 Student(学生)类的对象与学生类关联。

Reference.png

原文:

When do we use Aggregation ??
Code reuse is best achieved by aggregation.

译文:

我们什么时候使用聚合?
代码复用最好通过聚合实现。

原文:

Composition

Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.

  • It represents part-of relationship.
  • In composition, both the entities are dependent on each other.
  • When there is a composition between two entities, the composed object cannot exist without the other entity.

原文:

组合

组合是聚合的一个受限制形式,其中的两个实例之间相互高度依赖。

  • 它代表了‘part-of’(一部分)的关系。
  • 在组合中,两个实例之间相互依赖
  • 如果两个实例之间有组合关系,合成对象不能脱离另一个实例存在。

原文:

Lets take example of Library.

译文:

让我们用图书馆举例。

// Java program to illustrate 
// the concept of Composition 
import java.io.*; 
import java.util.*; 

// class book 
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; 
    } 
    
} 

// main method 
class GFG 
{ 
    public static void main (String[] args) 
    { 
        
        // Creating the Objects of Book class. 
        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 the 
        // no. of books. 
        List<Book> books = new ArrayList<Book>(); 
        books.add(b1); 
        books.add(b2); 
        books.add(b3); 
        
        Library library = new Library(books); 
        
        List<Book> bks = library.getTotalBooksInLibrary(); 
        for(Book bk : bks){ 
            
            System.out.println("Title : " + bk.title + " and "
            +" Author : " + bk.author); 
        } 
    } 
} 

原文:

Output

译文:

输出

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

原文:

In above example a library can have no. of books on same or different subjects. So, If Library gets destroyed then All books within that particular library will be destroyed. i.e. book can not exist without library. That’s why it is composition.

译文:

在上面的例子中,一个图书馆可以有一系列相同或不同科目的书,如果图书馆被摧毁,那么里面所有的书会被毁掉。也就是,书不能脱离图书馆存在。这也是成为组合的理由。

原文:

Aggregation vs Composition

译文:

聚合与组合

原文:

  1. Dependency: Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human
  2. Type of Relationship: Aggregation relation is “has-a” and composition is “part-of” relation.
  3. Type of association: Composition is a strong Association whereas Aggregation is a weak Association.

译文:

  1. 依赖性:聚合意味着一个关系:子实例可以独立于父实例存在。例如,银行和顾员,删除银行,顾员仍然存在。然而组合意味着一个关系:子实例不可以独立于父实例存在。例如,人和心脏,心脏不能离开人。
  2. 关系类型:聚合关系是 “has-a” (有一个),组合关系是“part-of”(一部分)。
  3. 关联类型:组合是一个强关联,而聚合是一个弱关联。
// Java program to illustrate the 
// difference between Aggregation 
// Composition. 
  
import java.io.*; 
  
// Engine class which will  
// be used by car. so 'Car' 
// class will have a field  
// of Engine type. 
class Engine  
{ 
    // starting an engine. 
    public void work() 
    { 
          
        System.out.println("Engine of car has been started "); 
          
    } 
      
} 
  
// Engine class 
final class Car  
{ 
      
    // For a car to move,  
    // it need to have a engine. 
    private final Engine engine; // Composition 
    //private Engine engine;     // Aggregation 
      
    Car(Engine engine) 
    { 
        this.engine = engine; 
    } 
      
    // car start moving by starting engine 
    public void move()  
    { 
          
        //if(engine != null) 
        { 
            engine.work(); 
            System.out.println("Car is moving "); 
        } 
    } 
} 
  
class GFG  
{ 
    public static void main (String[] args)  
    { 
          
        // making an engine by creating  
        // an instance of Engine class. 
        Engine engine = new Engine(); 
          
        // Making a car with engine. 
        // so we are passing a engine  
        // instance as an argument while 
        // creating instace of Car. 
        Car car = new Car(engine); 
        car.move(); 
          
    } 
} 

原文:

Output:

译文:

输出:

Engine of car has been started 
Car is moving 

原文:

In case of aggregation, the Car also performs its functions through an Engine. but the Engine is not always an internal part of the Car. An engine can be swapped out or even can be removed from the car. That’ why we make The Engine type field non-final.

译文:

在聚合的情形中,Car(汽车) 能通过一个Engine(引擎)工作。但是引擎通常不是汽车内部的一部分。一个引擎可以被替换甚至从汽车中移除。这是我们把Engine类的成员变量定义成non-final的原因。

原文:

This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

译文:

这篇文章由Nitsdheerendra贡献,如果你喜欢GeeksforGeeks并且想投稿,你也可以用 contribute.geeksforgeeks.org 写一篇文章,或者把你的文章发送到contribute@geeksforgeeks.org。期待你的文章出现在GeeksforGeeks 上,并且能帮助其他极客。

原文:

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

译文:

如果你发现任何错误,或者想分享更多关于以上话题的信息,请写评论。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,102评论 0 10
  • 早上6点07分起床在群里打卡,还是迟到了7分钟。觉察到自己改变的决心还不够。7点40送陈燃到学校后去公司参加早会,...
    31c47a10aded阅读 310评论 0 0
  • 烟和酒 咖啡和高热量食品 麻醉之后 假装陶醉 毛衣和冷风 黑夜和台灯 我不说话 就不心疼.
    小酿不喜欢深蓝阅读 262评论 1 7
  • 作者:北名东 辽北四月苦伤春 雪去风来旱无荫 万亩良田唯盼雨 千里新畴静待云 天南乍起惊雷鼓 漠北忽来寄雨氛 蔽日...
    北名文学阅读 292评论 0 0
  • https://techblog.toutiao.com/2017/01/17/iosspeed/
    iYeso阅读 295评论 0 0