在“深层”对象层次结构中使用构建器模式的最佳实践是什么?为了详细说明,我探索了将 Joshua Bloch 提出的 Builder 模式应用到我的 XML 绑定代码的想法(我使用的是 SimpleXML,但这个问题适用于任何情况)。我的对象层次结构有 4 层深,具有不同程度的复杂性。我的意思是,在某些关卡中,我的对象只有几个属性,而在其他一些关卡中,我的对象最多有 10 个属性。
所以考虑这个假设的例子(为了简洁起见,我省略了简单的 XML 注释)
public class Outermost {
private String title;
private int channel;
private List<Middle> middleList;
}
class Middle {
private int id;
private String name;
private boolean senior;
/* ... ... 10 such properties */
private Innermost inner;
}
class Innermost {
private String something;
private int foo;
/* ... Few more of these ..*/
}
如果我想使用构建器强制创建
Outermost
对象,最好的方法是什么?最明显的答案是为上述每个类别设置 inner static Builder
类别。
但是,这不会让事情变得像构建器模式试图解决的问题一样难以处理吗?我正在考虑这样的事情 - 这将强制执行“由内而外”的方法 - 这意味着
Innermost
对象必须完全构造并实例化,然后才能添加到 Middle
对象。但我们都知道,在实践中(尤其是在构建 XML 或 JSON 时),我们很少有“及时”信息来完成这一任务。
很可能,最终每个级别的每个属性都会有变量;并在最后创建对象。或者,最终会在代码中出现多个级别的 Builder,从而增加混乱。
那么,关于如何优雅地实现这一点有什么想法吗?
这里对构建器模式的描述我猜你指的是;它与维基百科here中描述的模式有点不同,我更喜欢前者。
我没有看到您对构建顺序或封装损失的担忧不可避免地从我读到的描述中得出。对我来说,最大的问题是原始数据的结构。假设我们有
public OuterBuilder {
// some outer attributes here
private ArrayList<MiddleBuilder> m_middleList;
public OuterBuild( mandatory params for Outers ){
// populate some outer attributes
// create empty middle array
}
public addMiddle(MiddleBuilder middler) {
m_middleList.add(middler);
}
}
现在我们可以根据需要创建任意数量的 middleBuilder
while (middleDataIter.hasNext() ) {
MiddleData data = middleDateIter.next();
// make a middle builder, add it.
}
我们可以将相同的模式应用于更高级别的嵌套。
为了解决你的第一点,每个属性都有一个变量:取决于我们如何设计构建器以及我们的数据来自哪里。如果我们来自 UI,那么我们几乎每个属性都有一个变量,我们的情况也不会更糟。如果按照我上面的建议,我们正在迭代某些数据结构,那么构建器可能负责解释该数据结构。在我的示例中,我们向下传递 MiddleData 实例。一些额外的耦合,但它确实封装了细节。
为了解决你的第二点,我们不会边走边构建东西,而是有效地使用构建器作为数据的积累点。最终我们调用“Go and Build”方法,但此时我们应该拥有所有数据,以便构建整个层次结构。
class Shape
{
private final double opacity;
public double getOpacity()
{
return opacity;
}
public static abstract class Builder<T extends Shape> {
private double opacity;
public Builder<T> opacity(double opacity) {
this.opacity = opacity;
return this;
}
public abstract T build();
}
public static Builder<?> builder() {
return new Builder<Shape>()
{
@Override
public Shape build()
{
return new Shape(this);
}
};
}
protected Shape(Builder<?> builder) {
this.opacity = builder.opacity;
}
}
class Rectangle extends Shape {
private final double height;
private final double width;
public double getHeight()
{
return height;
}
public double getWidth()
{
return width;
}
public static abstract class Builder<T extends Rectangle> extends Shape.Builder<T> {
private double height;
private double width;
public Builder<T> height(double height) {
this.height = height;
return this;
}
public Builder<T> width(double width) {
this.width = width;
return this;
}
}
public static Builder<?> builder() {
return new Builder<Rectangle>()
{
@Override
public Rectangle build()
{
return new Rectangle(this);
}
};
}
protected Rectangle(Builder<?> builder) {
super(builder);
this.height = builder.height;
this.width = builder.width;
}
}
...很快就遇到了问题。如果你尝试类似的事情
Rectangle r = Rectangle.builder().opacity(0.5).height(50).width(100).build();
它不会编译,因为
opacity()
不知道它返回一个
Rectangle.Builder
,只是一个
Shape.Builder<Rectangle>
。因此,您必须按从派生最多到派生最少的顺序调用属性:
Rectangle r = Rectangle.builder().height(50).width(100).opacity(0.5).build();
如果你想解决这个问题,你需要使属性方法通用,以便超类方法仍然返回子类构建器。据我所知,不可能做到 100% 可靠,但通过一些自引用泛型,您可以接近:
class Shape
{
private final double opacity;
public double getOpacity ()
{
return opacity;
}
public static abstract class ShapeBuilder<S extends Shape, B extends ShapeBuilder<S, B>>
{
private double opacity;
@SuppressWarnings( "unchecked" )
public B opacity ( double opacity )
{
this.opacity = opacity;
return (B) this;
}
public abstract S build ();
}
private static class DefaultShapeBuilder extends ShapeBuilder<Shape, DefaultShapeBuilder>
{
@Override
public Shape build ()
{
return new Shape( this );
}
}
public static ShapeBuilder<?, ?> builder ()
{
return new DefaultShapeBuilder();
}
protected Shape ( ShapeBuilder<?, ?> builder )
{
this.opacity = builder.opacity;
}
}
class Rectangle extends Shape
{
private final double height;
private final double width;
public double getHeight ()
{
return height;
}
public double getWidth ()
{
return width;
}
public static abstract class RectangleBuilder<S extends Rectangle, B extends RectangleBuilder<S, B>> extends ShapeBuilder<S, B>
{
private double height;
private double width;
@SuppressWarnings( "unchecked" )
public B height ( double height )
{
this.height = height;
return (B) this;
}
@SuppressWarnings( "unchecked" )
public B width ( double width )
{
this.width = width;
return (B) this;
}
}
public static RectangleBuilder<?, ?> builder ()
{
return new DefaultRectangleBuilder();
}
protected Rectangle ( RectangleBuilder<?, ?> builder )
{
super( builder );
this.height = builder.height;
this.width = builder.width;
}
private static class DefaultRectangleBuilder extends RectangleBuilder<Rectangle, DefaultRectangleBuilder>
{
@Override
public Rectangle build ()
{
return new Rectangle( this );
}
}
}
class RotatedRectangle extends Rectangle
{
private final double theta;
public double getTheta ()
{
return theta;
}
public static abstract class RotatedRectangleBuilder<S extends RotatedRectangle, B extends RotatedRectangleBuilder<S, B>> extends Rectangle.RectangleBuilder<S, B>
{
private double theta;
@SuppressWarnings( "Unchecked" )
public B theta ( double theta )
{
this.theta = theta;
return (B) this;
}
}
public static RotatedRectangleBuilder<?, ?> builder ()
{
return new DefaultRotatedRectangleBuilder();
}
protected RotatedRectangle ( RotatedRectangleBuilder<?, ?> builder )
{
super( builder );
this.theta = builder.theta;
}
private static class DefaultRotatedRectangleBuilder extends RotatedRectangleBuilder<RotatedRectangle, DefaultRotatedRectangleBuilder>
{
@Override
public RotatedRectangle build ()
{
return new RotatedRectangle( this );
}
}
}
class BuilderTest
{
public static void main ( String[] args )
{
RotatedRectangle rotatedRectangle = RotatedRectangle.builder()
.theta( Math.PI / 2 )
.width( 640 )
.height( 400 )
.height( 400 )
.opacity( 0.5d ) // note attribs can be set in any order
.width( 111 )
.opacity( 0.5d )
.width( 222 )
.height( 400 )
.width( 640 )
.width( 640 )
.build();
System.out.println( rotatedRectangle.getTheta() );
System.out.println( rotatedRectangle.getWidth() );
System.out.println( rotatedRectangle.getHeight() );
System.out.println( rotatedRectangle.getOpacity() );
}
}
注意
@SuppressWarnings
注释;如果子类打破了
FooBuilder
总是扩展
FooSuperclassBuilder<Foo, FooBuilder>
的约定,系统就会崩溃。你可以看到代码变得多么丑陋。此时,也许最好放弃
jaxb2-rich-contract-plugin 的“fluence-builder”插件将为您提供帮助。它生成一个深度构建器模式,您可以将构建器链接在一起,并使用“end()”方法完成构建嵌套对象并返回到其父级的构建器上下文。 然而,为给定的 Java 类手动编写这个似乎有点乏味......