使用lombok的@Builder继承和Jackson

时间:2017-06-14 19:28:04

标签: java design-patterns jackson lombok builder-pattern

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

我正在构建来自https://reinhard.codes/2015/09/16/lomboks-builder-annotation-and-inheritance/https://gist.github.com/pcarrier/14d3a8e249d804cfbdeeBuilder pattern with inheritance

的内容

这是我的

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
    }
}

根据用户选择,应使用相应的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!! stuck?
       }
}

ChoiceAttributesForChoice1.java

@JsonDeserialize(builder = ChoiceAttributesForChoice1.ChoiceAttributesForChoice1Builder.class)
@Builder
@Data
public class ChoiceAttributesForChoice1 extends ChoiceAttributes {
    private int x;
    //and so on

    @JsonPOJOBuilder(withPrefix = "")
    public static class ChoiceAttributesForChoice1Builder extends ChoiceAttributesBuilder {
    }
}

ChoiceAttributesForChoice2.java

@JsonDeserialize(builder = ChoiceAttributesForChoice2.ChoiceAttributesForChoice2Builder.class)
@Builder
@Data
public class ChoiceAttributesForChoice2 extends ChoiceAttributes {
    private float y;
    //and so on

    @JsonPOJOBuilder(withPrefix = "")
    public static class ChoiceAttributesForChoice2Builder extends ChoiceAttributesBuilder {
    }
}

有没有更好的方法来实现这一目标?我如何构建" UserInput"使用基于UsersChoice的构建器和ChoiceAttribute?

0 个答案:

没有答案