我在 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);
}
}