Can I use the builder pattern on a Java Enum

前端 未结 3 945
粉色の甜心
粉色の甜心 2021-02-05 11:26

I\'m re-writing some code, and I\'ve decided the way to recreate the class, as there are a fixed number of sheets, I\'m creating them as enums. This is a decision based on the r

3条回答
  •  粉色の甜心
    2021-02-05 11:41

    mySheet1, mySheet2, etc. are enum constants which follows the JLS syntax defined in section 8.9.1

    EnumConstant: Annotationsopt Identifier Argumentsopt ClassBodyopt

    So, you can follow the enum constant by an argument list (the parameters to pass to the constructor) but you can't call a method on the enum constant while declaring it. At most you can add a class body for it.

    Beside this, your usage of builder pattern to build enum instances is questionable as in general the builder pattern is used when you have a large number of instances (combinations of field values) in contrast with the concept of enums used for a few instances.

提交回复
热议问题