0

我在 Web 应用程序的 Handler 类中有一个静态 StringWriter 变量,由该类中的多个私有方法使用。每个方法都将一个字符串附加到这个变量,最后 StringWriter 将连接的字符串写入文件。但是在测试 Web 应用程序时,我意识到 StringWriter 仍然保存着之前所有测试的值。我使用了这个问题的答案(How do you "empty" a StringWriter in Java?)作为一种解决方法,但我觉得这在设计模式和安全性方面是不正确的。

这是对的吗?有没有更好的办法?

public class BaseHandler {
    private static StringWriter sw = new StringWriter();

    public static void writeToFile(){
        firstMethod();
        secondMethod();
        finalMethod(); 
    }
    private static void firstMethod(){
        sw.append("Pandora's");
    }

    private static void secondMethod(){
        sw.append("Box");
    }

    private static void finalMethod(){
        sw.append("!");
        //sw writes value to file
        ...
        sw.getBuffer().setLength(0);
    }
}
4

1 回答 1

1

我会问自己,我需要一个保持状态的 BaseHandler 吗?现在您的处理程序在sw字段中保存了一个状态,但如果您不需要此状态,则无需创建字段。

例如,您可以这样做:

public class BaseHandler {


    public static void writeToFile(){
        StringWriter sw = new StringWriter();
        firstMethod(sw);
        secondMethod(sw);
        finalMethod(sw); 
    }
    private static void firstMethod(StringWriter sw){
        sw.append("Pandora's");
    }

    private static void secondMethod(StringWriter sw){
        sw.append("Box");
    }

    private static void finalMethod(StringWriter sw){
        sw.append("!");
        //sw writes value to file
        ...
    }
}

退出 writeToFile,StringWriter 被标记为垃圾回收。

于 2017-03-28T19:46:22.800 回答