3 回答

TA貢獻1805條經(jīng)驗 獲得超10個贊
如果do1等只是實現(xiàn),而不是類的公共接口的一部分,那么創(chuàng)建一個私有類(甚至可能是嵌套類)可能是有意義的,它的構造函數(shù)接受它作為實例變量保留的兩個映射:
private static class Worker {
Worker(Map firstMap, Map secondMap) {
this.firstMap = firstMap;
this.secondMap = secondMap;
}
void do1() {
// ...update `this.lastMap` if appropriate...
}
void do2() {
// ...update `this.lastMap` if appropriate...
}
}
我在那里做了Worker static一個靜態(tài)嵌套類,而不是內部類,但static如果您需要訪問周圍類的內部結構,它可以是內部類(否)。
然后
public Map<String, Object> transformMapOnAnotherMap(Map<String, Object> firstMap) {
Worker worker = new Worker(firstMap, new HashMap<String, Object>(firstMap));
worker.do1();
worker.do2();
worker.do3();
worker.do4();
//more 20 methods
return worker.lastMap;
}

TA貢獻1865條經(jīng)驗 獲得超7個贊
您可以使用interface并使每個“做”功能接口的實現(xiàn)。
interface Do {
Map<String, Object> apply(Map<String, Object> firstMap, Map<String, Object> lastMap);
}
然后你可以初始化 static dos:
static Do[] allDos = {
(firstMap, lastMap) -> {
// do0
},
(firstMap, lastMap) -> {
// do1
},
// ...do2, do3, ...
};
如果您需要調用do0 -> do2 -> do4例如:
public Map<String, Object> transformMapOnAnotherMap(Map<String, Object> firstMap) {
Map<String, Object> lastMap = new HashMap<String, Object>(firstMap);
int[] ids = { 0, 2, 4 };
for (int id : ids)
lastMap = allDos[id].apply(firstMap, lastMap);
return lastMap;
}

TA貢獻1817條經(jīng)驗 獲得超6個贊
為什么不采取更多的功能方法?
定義接口
interface MapTransformation{
void transformation(Map<String, Object> first, Map<String, Object> last);
}
然后在類創(chuàng)建期間,具有定義的類transformMapOnAnotherMap將轉換列表作為參數(shù)然后你可以做
class SomeClass {
final private List<MapTransformation> transformations;
//constructor omitted
public Map<String, Object> transformMapOnAnotherMap(Map<String, Object> firstMap) {
Map<String, Object> lastMap = new HashMap<String, Object>(firstMap);
transformations.forEach(t->t.transformation(firstMap,lastMap);
return lastMap;
}
}
添加回答
舉報