泛型-在泛型类型的对象上扩展构建器模式

时间:2018-08-10 23:52:25

标签: java generics builder

我一直试图在Java中实现可扩展的Builder模式,该模式将非静态内部类用于生成器。我已经能够实现这一目标,但是遇到了一个我不理解的问题。当我向封闭的类(正在构建的东西)添加泛型类型时,流畅的接口就坏了。也就是说,父级的builder方法返回的类型不再是子级类型。

package inh;

public class Rabbit<T> {

public Rabbit(){}

private String rabbit;

public String getRabbit(){
    return rabbit;
}

public Rabbit(ParentBuilder b){
    rabbit = b.rabbit;
}


public abstract class ParentBuilder<B extends Rabbit<T>.ParentBuilder<B>>{

    public ParentBuilder(){}

    private String rabbit;

    public B withRabbit(){
        rabbit = "Rabbit";
        return getThis();
    }

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

    public abstract B getThis();


}

}

子类如下:

public class RabbitChild<T> extends Rabbit<T>{

public RabbitChild(){}

public RabbitChild(ChildBuilder builder){
    this.babyRabbit = builder.babyRabbit;
}

private String babyRabbit;

public String getBabyRabbit(){
    return babyRabbit;
}

public class ChildBuilder extends Rabbit<T>.ParentBuilder<ChildBuilder>{

    private String babyRabbit;

    public ChildBuilder withBabyRabbit(){
        babyRabbit = "BabyRabbit";
        return this;
    }

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

    @Override
    public RabbitChild<T>.ChildBuilder getThis() {
        return this;
    }
}


}

删除“ T”泛型使withRabbit返回类型成为ChildBuilder,但我不知道为什么。可以在保留通用类型的同时做到这一点吗?

0 个答案:

没有答案