我有这个类,我在这个类上有一个方法并将返回一个映射,使用其中的许多方法使用相同的参数。
我的类(class)有几千行,而且还会增加。
我可以创建几个类和内部创建方法,但我想问一下是否有针对这种情况的特殊设计
实际场景:
public Map<String, Object> transformMapOnAnotherMap(Map<String, Object> firstMap) {
Map<String, Object> lastMap = new HashMap<String, Object>(firstMap);
lastMap = do1(firstMap, lastMap);
lastMap = do2(firstMap, lastMap);
lastMap = do3(firstMap, lastMap);
lastMap = do4(firstMap, lastMap);
//more 20 methods
return lastMap;
}
尝试无设计:
public Map<String, Object> transformMapOnAnotherMap(Map<String, Object> firstMap) {
Map<String, Object> lastMap = new HashMap<String, Object>(firstMap);
Do1 do1 = new Do1();
lastMap = do1.do1(firstMap, lastMap);
Do2 do2 = new Do2();
lastMap = do2.do2(firstMap, lastMap);
// more 20 methods
return lastMap;
}
最佳答案
如果 do1
等只是实现,而不是类的公共(public)接口(interface)的一部分,那么创建一个带有构造函数的私有(private)类(甚至可能是嵌套类)可能是有意义的接受它保留的两个映射作为实例变量:
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
所以它是一个静态嵌套类,而不是内部类,但它可以是一个内部类(不是 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;
}
关于java - 使用相同参数的多个方法的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51820212/