我认为使用辅助方法(未经测试的代码)可以更轻松地处理这个问题:
public String myMethod() {
StringBuilder sb = new StringBuilder();
addToBuffer(sb, "Hello").addToBuffer("there,");
addToBuffer(sb, "it").addToBuffer(sb, "works");
}
private StringBuilder addToBuffer(StringBuilder sb, String what) {
return sb.append(what).append(' '); // char is even faster here! ;)
}
甚至使用具有流畅界面的Builder模式(也是未经测试的代码):
public String myMethod() {
SBBuilder builder = new SBBuilder()
.add("Hello").add("there")
.add("it", "works", "just", "fine!");
for (int i = 0; i < 10; i++) {
builder.add("adding").add(String.valueOf(i));
}
System.out.println(builder.build());
}
public static class SBBuilder {
private StringBuilder sb = new StringBuilder();
public SBBuilder add(String... parts) {
for (String p : parts) {
sb.append(p).append(' '); // char is even faster here! ;)
}
return this;
}
public String build() {
return sb.toString();
}
}
这是关于这个主题的article.
希望能帮助到你! 🙂