相关疑难解决方法(0)

多态对象层次结构的构建器模式:Java可能吗?

我有一个接口层次结构,有Child实现Parent.我想使用不可变对象,所以我想设计Builder一些方便地构造这些对象的类.但是,我有很多Child接口,我不想Parent在每种类型的子构建器中重复构建s 的代码.

因此,假设以下定义:

public interface Parent {
    public Long getParentProperty();
}

public interface Child1 extends Parent {
    public Integer getChild1Property(); 
}

public interface Child2 extends Parent {
    public String getChild2PropertyA();
    public Object getChild2PropertyB();
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能有效地实施构建器Child1BuilderChild2Builder?他们应该支持以下操作:

Child1 child1 = Child1Builder.newChild1().withChild1Property(5).withParentProperty(10L);
Run Code Online (Sandbox Code Playgroud)

Child2 child2 = Child2Builder.newChild2().withChild2PropertyA("Hello").withParentProperty(10L).withChild2PropertyB(new Object());
Run Code Online (Sandbox Code Playgroud)

我不想withParentProperty为每个子构建器实现特殊情况.

编辑添加第二个属性,Child2以澄清这不能用简单的泛型.我不是在寻找一种方式来组合Child1Child2-我正在寻找一种方式来实现Builder,不重复建设的父类为每个子类的工作体系.

谢谢你的帮助!

java design-patterns builder

22
推荐指数
2
解决办法
1万
查看次数

在继承和杰克逊中使用lombok的@Builder

我正在尝试将lombok的@Builder与继承和Jackson一起使用。

我是从建筑的东西https://reinhard.codes/2015/09/16/lomboks-builder-annotation-and-inheritance/https://gist.github.com/pcarrier/14d3a8e249d804cfbdee建设者遗传模式

这是我所拥有的

UserInput.java

@JsonDeserialize(builder = UserInput.UserInputBuilder.class)
@Builder
@Data
public class UserInput {
    private int userId;
    private UsersChoice usersChoice;
    private ChoiceAttributes choiceAttributes;

    @JsonPOJOBuilder(withPrefix = "")
    public static final class UserInputBuilder {

    }

    public enum UserChoice {
          CHOICE1,
          CHOICE2
    }
}
Run Code Online (Sandbox Code Playgroud)

基于用户的选择,应使用相应的ChoiceAttributes构建器。

ChoiceAttributes.java

public abstract class ChoiceAttributes {
    //nothing to do here
    public static class ChoiceAttributesBuilder {
    }

    public static ChoiceAttributesBuilder getMeMyBuilderBasedOnUserChoice(UserChoice userChoice)
    {
       ChoiceAttributesBuilder choiceAttributesBuilder = null;
       switch(userChoice){
            case CHOICE1:
                choiceAttributesBuilder = new ChoiceAttributesForChoice1.ChoiceAttributesForChoice1Builder(); //err!! …
Run Code Online (Sandbox Code Playgroud)

java design-patterns builder-pattern jackson lombok

5
推荐指数
0
解决办法
641
查看次数