0
我有一個從xml映射的類。爲了簡單起見,讓我們來想象這個類是這樣的:如何避免讓不同的方法循環同一個列表?
class Employee implements EmployeeIF {
Map<AttributeIF,Object> attribute = new HashMap<>();
@Override
public Map<AttributeIF,Object> getAttributes() { return attribute; }
}
這是我不能改變的東西。
現在,現有的代碼充滿了類似的方法:
public int getSalary(EmployeeIF employee) {
for(Entry<AttributeIF,Object> entry : employee.getAttributes()) {
if(entry.getKey().getName().equals("salary")) return (Integer)entry.getValue();
}
return 0;
}
public int getAddress(EmployeeIF employee) {
for(Entry<AttributeIF,Object> entry : employee.getAttributes()) {
if(entry.getKey().getName().equals("address")) return (String)entry.getValue();
}
return "";
}
...等等。當然你明白了。
我需要包括一個新的方法返回從員工一個新的屬性,但我覺得這是可怕的十個分量,我拒絕只需添加一個新的方法存在。 我正在考慮使用動作模式,以避免至少重複againg和for循環,但我不得不說,我找不到一個聰明的解決方案。
什麼是你的選擇?
感謝, 丹妮。
Pd積是的,我想是這樣
private Object getAttribute(EmployeeIF employee, String attribute)
您在'Map'工作,爲什麼難道你不使用it's關鍵的,直接從鑰匙獲得的價值? – SomeJavaGuy
我無法更改屬性MapIF,它是地圖的關鍵。這也是自動生成的。 –
您必須在Employee類中重寫equals()方法。然後你可以使用map.get()調用。 – Sunny