使用超类创建构建器时,父级不能返回子类的实例

时间:2016-03-12 20:38:15

标签: java design-patterns builder

如果我使用构建器模式配置新对象,我可能有两个类,如GameHockeyGame(如下所示)。当我想创建一个新的HockeyGame时,我得到它的构建器并开始调用方法来根据需要配置对象。

我遇到的问题显示在main函数中。一旦我从超类中调用一个方法,它就会返回Game.Builder的intance,我不能再调用子类中的任何方法。

处理此问题的最佳方法是什么?

Main.java

class Main {

    public static void main(String[] args){

        HockeyGame hg = new HockeyGame.Builder()
                .setScore(5)
                .setTimeLimit(3600)
//--------------------------------------------------------------------
                .setIceTemperature(-5) // Error! Cannot call setIceTempurature() on
                                       // an instance of Game.Builder
//--------------------------------------------------------------------
                .build();


    }
}

Game.java

public class Game{

    int score;
    int timeLimit;

    public Game(int score, int timeLimit) {
        this.score = score;
        this.timeLimit = timeLimit;
    }

    public static class Builder {

        int score;
        int timeLimit;

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

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

        public Game build() {
            return new Game(score, timeLimit);
        }
    }
}

HockeyGame.java

public class HockeyGame extends Game {

    float iceTemperature;

    public HockeyGame(int score, int timeLimit, float iceTemperature) {
        super(score, timeLimit);
        this.iceTemperature = iceTemperature;
    }

    public static class Builder extends Game.Builder {

        float iceTemperature;

        public HockeyGame.Buidler setIceTemperature(float iceTemperature) {
            this.iceTemperature = iceTemperature;
            return this;
        }

        public HockeyGame build(){
            return new HockeyGame(score, timeLimit, iceTemperature);
        }
    }
}

感谢。

2 个答案:

答案 0 :(得分:5)

您需要使用流畅的API代码中常见的getThis()技巧。

首先,您需要在本身中创建Game.Builder泛型:

public static class Builder<B extends Builder<B>>

然后添加getThis()方法:

public B getThis() {
    return (B) this;
}

现在,您更改自的设置者以返回Breturn getThis()而不是this

public B setTimeLimit(int timeLimit) {
    //...
    return getThis();
}

您的扩展类本身也需要是通用的:

public static class Builder<B extends Builder<B>> extends Game.Builder<B>

现在你可以使用代码了,它会记住&#34;预期类型:

HockeyGame hockeyGame = new HockeyGame.Builder<>().setScore(10)
        .setTimeLimit(20)
        .setIceTemperature(-1)
        .build();

这个最终代码类似于:

public class Game {

    private final int score;
    private final int timeLimit;

    private Game(final Builder<?> builder) {
        this.score = builder.score;
        this.timeLimit = builder.timeLimit;
    }

    public static class Builder<B extends Builder<B>> {

        private int score;
        private int timeLimit;

        public B setScore(int score) {
            this.score = score;
            return getThis();
        }

        public B setTimeLimit(int timeLimit) {
            this.timeLimit = timeLimit;
            return getThis();
        }

        protected B getThis() {
            return (B) this;
        }

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

public class HockeyGame extends Game {

    private final float iceTemperature;

    private HockeyGame(final Builder<?> builder) {
        super(builder);
        this.iceTemperature = builder.iceTemperature;
    }

    public static class Builder<B extends Builder<B>> extends Game.Builder<B> {

        private float iceTemperature;

        public B setIceTemperature(float iceTemperature) {
            this.iceTemperature = iceTemperature;
            return getThis();
        }

        @Override
        public HockeyGame build() {
            return new HockeyGame(this);
        }
    }
}

N.B:我创建了字段private final以及主要类型构造函数 - 这迫使人们使用Builder。此外,构造函数可以使用Builder<?>并从那里复制变量 - 这会稍微整理一下代码。

正如您可能已经注意到的那样,实际的黑客是:

public B getThis() {
    return (B) this;
}

在这里,我们强制将Builder转换为其泛型类型 - 这允许我们根据所使用的特定实例更改方法的返回类型。问题是,如果您声明一个新的Builder,如下所示:

public static class FootballGame extends Game {

    private FootballGame(final Builder<?> builder) {
        super(builder);
    }

    public static class Builder<B extends HockeyGame.Builder<B>> extends Game.Builder<B> {

        float iceTemperature;

        @Override
        public FootballGame build() {
            return new FootballGame(this);
        }
    }
}

这将在运行时以ClassCastException爆炸。但setter方法会返回HockeyGame.Builder而不是FootballGame.Builder,因此问题应该很明显。

答案 1 :(得分:0)

尝试这样的事情

您明确地将其强制转换回HockeyGame.Builder对象,并使用自己的方法。

你遇到的问题是setTimeLimit返回一个Builder对象(母类),因此你不能在其上使用子方法。

HockeyGame hg = ((HockeyGame.Builder)(new HockeyGame.Builder().setScore(5)
                                                              .setTimeLimit(3600)))
                                                              .setIceTemperature(-5)
                                                              .build();

此外,setIceTemparature应该返回一个HockeyGame.Builder对象,以便能够build

public Builder setIceTemperature(float iceTemperature) {
    this.iceTemperature = iceTemperature;
    return this;
}