Java StringBuilder在追加调用之间删除新行?

时间:2012-12-06 16:32:50

标签: java append stringbuilder

是否可以配置Java StringBuilder类在每次追加调用之间追加一个新行?

1 个答案:

答案 0 :(得分:3)

我认为StringBuilder内置了该功能。既然你不能只扩展它,你可以尝试使用装饰器模式......

class NewlineStringBuilder {

    private StringBuilder delegate;

    public NewlineStringBuilder() {
        delegate = new StringBuilder();
    }

    public NewlineStringBuilder appendLine(String str) {
        delegate.append(str).append("\n");
        return this;
    }

    public String toString() {
        return delegate.toString();
    }
}

另外,Java可以支持这种简写,这很有用,因为装饰器不需要重新实现所有需要从装饰类中获得的方法,但是由于原始资源是完全未暴露的,所以它更危险,因此必须权衡权衡:

StringBuilder message = new StringBuilder();
class AppendingStringBuilder {
    private final StringBuilder builder;
    AppendingStringBuilder(StringBuilder builder) {
        this.builder = builder;
    }
    public AppendingStringBuilder append(String str) {
        builder.append(str + "\n");
        return this;
    }
}
AppendingStringBuilder messageHelper;
// ...