2

是否可以将 JavaStringBuilder类配置为在每次调用 append 之间附加一个新行?

4

1 回答 1

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;
// ...
于 2012-12-06T16:35:01.663 回答