1

我有一个名为 Box 和 PackageBox 的蹩脚测试类。Box 使用应该扩展 Box 的 Builder Pattern 和 PackageBox

这是一些代码

package console.app.model;

public class Box {

private String name = "";
private int weight = 0;
private int width = 0;
private int height = 0;

// Box instance for comparison on method equals().
private static Box comparisonBox;

public static class Builder {

    private String name = "";
    private int weight = 0;
    private int width = 0;
    private int height = 0;

    public Builder(String name) {
        this.name = name;
    }

    public Builder weight(int weight) {
        this.weight = weight;
        return this;
    }

    public Builder width(int width) {
        this.width = width;
        return this;
    }

    public Builder height(int height) {
        this.height = height;
        return this;
    }

    public Box build() {
        return new Box(this);
    }

}

private Box(Builder builder) {
    name = builder.name;
    weight = builder.weight;
    width = builder.width;
    height = builder.height;
}

    // Setters and getters, etc. 

}

如何将 Box 扩展到 PackageBox?谢谢,如果有问题,请告诉我或在 Box 类中替换。

4

1 回答 1

0

将受保护的构造函数添加到 Box,然后将其子类化,从 PackageBox 构造函数调用受保护的构造函数。但是,如果你想走这条路,你需要为 PackageBox 实现一个新的 Builder。

于 2013-08-28T23:47:27.503 回答