使用相同参数的多重方法的设计模式

时间:2018-08-13 10:28:03

标签: java design-patterns

我在这个类上有一个方法,并将使用相同的参数在其中使用许多方法来返回映射。

我的课有上千行,并且还会增加更多。

我可以创建几个类并在内部创建方法,但是我想问这种情况是否有特殊的设计

实际情况:

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;

}

3 个答案:

答案 0 :(得分:2)

如果LinkedList<Edge<T>> allAdjacents = new LinkedList<>(); for (Edge<T> edge : adjacencyList.get(vertex)) { allAdjacents.add(edge); } return allAdjacents; 等只是实现,而不是您的类的公共接口的一部分,那么创建一个私有类(也许甚至是一个嵌套类),并让构造函数接受这两个类可能是有意义的将其保留为实例变量的映射:

do1

我已经制作了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

答案 1 :(得分:1)

您可以使用interface并使每个“执行”功能接口的实现。

interface Do {
    Map<String, Object> apply(Map<String, Object> firstMap, Map<String, Object> lastMap);
}

然后您可以初始化静态do

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;
}

答案 2 :(得分:1)

为什么不采用更多功能性方法?

定义界面

interface MapTransformation{ 
     void transformation(Map<String, Object>  first, Map<String, Object>  last);
}

然后在创建类期间,定义为transformMapOnAnotherMap的类将转换列表作为参数,然后您就可以这样做

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;

    }
}