【问题标题】:How to set a base class fields with Immutables and the Egg pattern如何使用 Immutables 和 Egg 模式设置基类字段
【发布时间】:2020-04-28 15:58:38
【问题描述】:

我正在使用 Java 的 https://immutables.github.io/,但在使用基类和设置其字段一次时遇到问题。

我有使用 Egg 模式来共享字段的不可变对象,例如:

interface HousingBase {
  int streetNumber();
  String streetName();
  int zip();
}

@Value.Immutable
interface House extends HousingBase {
  long lotSize();
}

@Value.Immutable
interface Apartment extends HousingBase {
  int apartmentNumber();
}

问题是我的代码从一组HousingBase 字段构造这些对象,我最终得到了重复的代码,例如:

public ImmutableHouse toHouse(HouseLocation location) {
  return ImmutableHouse.builder()
    .setStreetNumber(location.number())
    .setStreetName(location.street())
    .setZip(location.zip())
    .setLotSize(location.size())
    .build();
}
public ImmutableApartment toHouse(ApartmentLocation location) {
  return ImmutableApartment.builder()
    .setStreetNumber(location.number())
    .setStreetName(location.street())
    .setZip(location.zip())
    .setApartmentNumber(location.complex())
    .build();
}

我真正想要的是设置HousingBase 字段的某种方式,以便它们被定义一次。像这样:

public ImmutableApartment toHouse(ApartmentLocation location) {
  return setBaseFields(ImmutableApartment.builder(), location)
    .setApartmentNumber(location.complex())
    .build();
}

private Builder setBaseFields(Builder builder, Location location) {
  return builder
    .setStreetNumber(location.number())
    .setStreetName(location.street())
    .setZip(location.zip())
} 

但我不知道如何让它工作,或者是否可以使用这个库。

【问题讨论】:

    标签: java builder base egg


    【解决方案1】:

    泛型!

    private static <B extends Builder> B setBaseFields(B builder, Location location) {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 2013-02-25
      • 1970-01-01
      • 2012-04-20
      • 2016-10-31
      • 1970-01-01
      相关资源
      最近更新 更多