2010-12-06 70 views
1

我理解理論上的差異,但代碼實現有什麼區別?有人可以提供一些例子嗎?Java中的組合與雙向關聯

+1

感謝您的答案。 http://stackoverflow.com/questions/4298177/association-vs-aggregation(第三個答案)也有幫助。 我有一個最後的不確定性,我希望有人可以解決。 我是否正確相信圖中相關類的實例http://img152.imageshack.us/img152/4981/21083939.png將不得不由圖中未顯示的類擁有(否則聚合關係會必須在整個班級和相關班級之間存在?)? – amax 2010-12-06 14:50:40

回答

0

組成實際上是單向關聯 - 除了語義上,我們將它解釋爲意思是「那件東西是這件東西的一部分」,而不是簡單地說「這件東西有對這件東西的引用」。

3

目的,我們有學生和大學

class University { 
    private final Set<Student> students = new HashSet<Student>(); 
    void addStudent(Student s){students.add(s);} 
} 

class Student { 
    private final String name; 
    public Student(String name) { 
     this.name = name; 
    } 
} 

我們以某種方式

University university = new University(); 
Student bob = new Student("Bob"); 
university.addStudent(bob); 

創造這些東西,知道我們需要知道在大學沒有鮑勃的研究。 因此,我們創造了一些新的方法,爲大學

boolean contains(Student student){ 
     for(Student s : students){ 
      if(s.equals(student)) return true; 
     } 
     return false; 
    } 

和,比做SMT像university.contains(bob)

但是,如果我們還沒有鏈接到uniwersity,會怎樣。我們需要問問鮑勃。但鮑勃不知道。所以我們從組合到雙向去創造smt像

class University { 
    private final Set<Student> students = new HashSet<Student>(); 
    void addStudent(Student s){ 
     students.add(s); 
     s.setUniversity(this); 
    } 
    boolean contains(Student student){ 
     for(Student s : students){ 
      if(s.equals(student)) return true; 
     } 
     return false; 
    } 
} 

class Student { 
    private final String name; 
    private University university; 
    public Student(String name) { 
     this.name = name; 
    } 
    void setUniversity(University u){ 
     university = u; 
    } 
    boolean doYouStudyInUniversity(){ 
     return university != null; 
    } 
} 
//ask 
bob.doYouStudyInUniversity(); 
+0

我們是否應該在構造函數中實施setUniversity和addStudent以確保在創建新學生時始終調用它們? – 2012-06-24 03:49:03