本文介绍了Java中的Generic Builder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个查找表的构建器,并使用如下所示。

I created a builder for a lookup table and using it as shown below.

public class RaceCodeDataBuilder {

    private RaceCode raceCode;  

    public RaceCodeDataBuilder() {
        raceCode = new RaceCode();
    }

    public RaceCodeDataBuilder code(String code) {
        raceCode.setCode(code);     
        return this;
    }

    public RaceCodeDataBuilder displayName(String displayName) {
        raceCode.setDisplayName(displayName);
        return this;
    }

    public RaceCode build() {
        return raceCode;
    }

}

一个测试:

   RaceCode mockRaceCode = new RaceCodeDataBuilder()
                         .code("2054-5")
                         .displayName("Black or African American")
                         .build();

我期待许多更多类似的构建器用于其他查找表,如StateCodeBuilder,GenderCodeBuilder和所有它们只有代码和displayName,类似于上面的构建器。

I am expecting lot more similar builders for other look up tables such as StateCodeBuilder, GenderCodeBuilder and all of them have just "code" and "displayName", similar to above builder.

我想创建一个通用的构建器,并避免创建几个同样的作业的构建器类不同的名字

I want to create a generic builder and avoid creating several builder classes doing the same job with different name.

我尝试了一些泛型的东西,但是我很开心..

I attempted something in generics but I am way off..

public class CodeDataBuilder<T>{

    private T t;    

    public CodeDataBuilder(T t) {
        this.t = t;
    }

    public CodeDataBuilder code(String code) {
        raceCode.setCode(code);     // Cant write T.setCode here for obvious resons
        return this;
    }

    public CodeDataBuilder displayName(String displayName) {
        raceCode.setDisplayName(displayName); // Cant write T.setDisplayNamehere for obvious resons
        return this;
    }

    public T build() {
        return t;
    }

}

有人可以帮助我吗?

谢谢。

推荐答案

创建界面 BuildableCodeData 使用您需要的方法,并使用类别 RaceData

Create an interface BuildableCodeData with the methods you need, and implement it with classes like RaceData.

你的代码将如下所示:

public interface BuildableCodeData {

  public void setCode(String code);

  public void setDisplayName(String name);
}

public class Builder<T extends BuildableCodeData> {
  private T codeData;

  public Builder(T codeData) {
    this.codeData = codeData;
  }

  public Builder<T> setCode(String code) {
    codeData.setCode(code);
    return this;
  }

  public Builder<T> setDisplayName(String displayName) {
    codeData.setDisplayName(displayName);
    return this;
  }

  public T build() {
    return codeData;
  }
}

这篇关于Java中的Generic Builder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 07:28