我想按照 joshua bloch 所说的方式实现构建器模式,但我也在使用 jackson 的 objectMapper 将一个对象转换为另一个对象,它在内部使用 setter 方法设置值。
将两者都放在一个类(class)是好的做法吗?或者如果不是,我怎样才能实现两全其美?
最佳答案
我从未尝试过,但显然 jackson 2.x 支持构建器模式
http://wiki.fasterxml.com/JacksonFeatureBuilderPattern
@JsonDeserialize(builder=ValueBuilder.class)
public class Value {
private final int x, y;
protected Value(int x, int y) {
this.x = x;
this.y = y;
}
}
public class ValueBuilder {
private int x, y;
// can use @JsonCreator to use non-default ctor, inject values etc
public ValueBuilder() { }
// if name is "withXxx", works as is: otherwise use @JsonProperty("x") or @JsonSetter("x")!
public ValueBuilder withX(int x) {
this.x = x;
return this; // or, construct new instance, return that
}
public ValueBuilder withY(int y) {
this.y = y;
return this;
}
public Value build() {
return new Value(x, y);
}
}
关于java - 具有 getter/setter 的构建器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22875013/