【发布时间】: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())
}
但我不知道如何让它工作,或者是否可以使用这个库。
【问题讨论】: