java - 使用相同参数的多个方法的设计模式

标签 java design-patterns

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

我的类(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/

相关文章:

java - 如何与 BLE 通信

java - 这个Java场景内存泄漏在哪里呢?

c# - 声明式和命令式模式是一种设计模式吗?

c# - 我的 DAL 应该返回 Person 还是 Datatable?

design-patterns - 前端 Controller 和 View 助手有什么区别

java - Android 中资源的动态命名,无需 getIdentifier

java - 找不到默认配置文件 [metro-default.xml]

java - 将阻塞 Socket 对象转换为 SocketChannel 的套接字?

c++ - 在 C++ 中组合接口(interface)

c# - C# 中的双向适配器和可插拔适配器模式有什么区别?