2013-08-16 484 views
2

在編程語言如Java中是否存在相應的表示法如下語句: Arrow on both ends means bidirectional relation, where both classes know about each other編程級的UML關聯

和確切classes know about each other

回答

1

「相互瞭解」是指參與該關係的每個類別的對象持有對其關聯方的參考。如:(*)

class Dog { 
    private Person owner; 
} 

class Person { 
    private Dog[] dogs; 
} 

這可能符合1:很多公會人與狗之間:

  • 每個人擁有許多狗(可能是沒有,如果狗陣列空)
  • 每狗最多隻有一個人擁有(如果owner爲空,則可能沒有擁有者)。

請注意,雙向性意味着寫訪問必須確保兩端的一致性。因此,例如,Dog.setOwner()也必須確保Person.dogs被正確更新(通過在Dog上調用適當的方法)。這是您爲雙向導航付出的代價。

如果您不需要導航兩種方式,您可以刪除其中一個參考。例如:

class Dog { 
    //no reference to owner 
} 

class Person { 
    private Dog[] dogs; 
} 

在這個例子中它不可能從狗到它的主人導航:但Person.dogs寫訪問器是相應簡單。

hth。

-

(*)請注意,這是貫徹落實協會事實上的方式。還有另外一種方法:將關係聲明爲一個類本身。這種方法使用得少得多 - 雖然對於有協會本身屬性的協會類可能很方便;例如

class DogOwnership { 
    private Person owner; 
    private Dog dog; 
    private License license; // license for this Person owning this Dog 
} 

但是,相同的規則適用於雙向訪問。