【问题标题】:How to implement builder pattern when class is extending Abstract class类扩展抽象类时如何实现构建器模式
【发布时间】:2019-06-07 12:39:00
【问题描述】:

尝试实现构建器模式,其中我有一个扩展抽象类服务输入的类契约

我已经创建了如下添加的合同生成器,但不知道如何访问 ServiceInput 的 userInfo。

*不能修改 ServiceInput 类,因为它来自不同的模块。

public class Contract extends ServiceInput{

String name;
..
}
public abstract class ServiceInput{

private UserInfo userInfo;
//getter
//setter
..
}
public class ContractBuilder{
String name;

public ContractBuilderwith(
            Consumer<ContractBuilder> builderFunction) {
        builderFunction.accept(this);
        return this;
    }

 public Contract createContract() {
 return new Contract(name);
}

}

【问题讨论】:

  • 也许你可以有一个抽象的 ServiceInputBuilder,负责设置 ServiceInput 特定的属性,ContractBuilder 会扩展它?
  • 要从你的builder中设置userInfo,你必须使用ServiceInput提供的方法和/或构造函数。

标签: java builder-pattern


【解决方案1】:

正如@Mauric 所建议的,能够使用ServiceInput 中的方法解决问题。 在 Contract 类构造函数中,我调用了 ServiceInput 方法来设置 userInfo,如下所示:

super.setUserInfo(userInfo);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多