假設我有下面的類什麼是從對象中返回嵌套集合的正確方法?
class Person{
long id;
List<Address> addresses;
public Person(long id){
this.id = id;
this.addresses = new ArrayList<Address>();
}
public long getId(){
return id;
}
//Implementation # 1
public List<Address> getAddresses(){
List<Address> addressesToReturn = new ArrayList<Address>();
for(Address address : addresses){
addressesToReturn.add(address.copy());
}
return addressesToReturn;
}
}
class Address{
String value;
public Address(String value){
this.value = value;
}
public Address copy(){
Address address = new Address(this.value);
return address;
}
}
在這種特殊情況下,getAddresses()
返回地址對象的副本的列表。我可以有兩個可選的實施方式如下:
//Implementation # 2
public List<Address> getAddresses(){
List<Address> addressesToReturn = new ArrayList<Address>();
for(Address address : addresses){
addressesToReturn.add(address); //i.e. return the original object as is
}
return addressesToReturn;
}
OR
//Implementation # 3
public List<Address> getAddresses(){
return addresses; //i.e return the original list.
}
現在,我知道我不應該使用第三實現,因爲我不希望某些外部代碼改變地址Person對象。
在第一個和第二個之間,我有點困惑。前兩種實現中的哪一種是首選的,特別是當我有某種數據存儲/數據庫來存儲所有人員對象時?
我想知道何時使用Implementation # 1
以及何時使用Implementation # 2
這個基於接口的解決方案真的很性感!謝謝 – Ankit