gpt4 book ai didi

java - 如果使用枚举,如何清理代码太多

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:44:07 28 4
gpt4 key购买 nike

我要编写以下代码。它采用一种枚举类型并返回其他枚举值。如何去除代码中过多的if else条件并使其干净?

private static QuestionType parseQuestionType(QuestionTypeInfo questionTypeInfo) {
if (questionTypeInfo instanceof OpenEndedTextQuestionTypeInfo) {
return QuestionType.OPEN_ENDED;
} else if (questionTypeInfo instanceof MultiChoiceQuestionTypeInfo) {
return QuestionType.MULTI_CHOICE;
} else if (questionTypeInfo instanceof MatrixSinglePerRowQuestionTypeInfo) {
return QuestionType.MATRIX_SINGLE_PER_ROW;
} else if (questionTypeInfo instanceof OpenEndedTextQuestionTypeInfo) {
return QuestionType.OPEN_ENDED;
} else if (questionTypeInfo instanceof MatrixMultiPerRowQuestionTypeInfo) {
return QuestionType.MATRIX_MULTI_PER_ROW;
} else if (questionTypeInfo instanceof MatrixSideBySideQuestionTypeInfo) {
return QuestionType.MATRIX_SIDE_BY_SIDE;
} else if (questionTypeInfo instanceof MatrixSpreadSheetQuestionTypeInfo) {
return QuestionType.MATRIX_SPREAD_SHEET;
} else if (questionTypeInfo instanceof DataListQuestionTypeInfo) {
return QuestionType.DATA_LIST;
} else if (questionTypeInfo instanceof FileUploadQuestionTypeInfo) {
return QuestionType.FILE_UPLOAD;
} else if (questionTypeInfo instanceof InteractiveSlidingScaleQuestionTypeInfo) {
return QuestionType.INTERACTIVE_SLIDING_SCALE;
} else if (questionTypeInfo instanceof NetPromoterQuestionTypeInfo) {
return QuestionType.NET_PROMOTER;
} else if (questionTypeInfo instanceof RankOrderQuestionTypeInfo) {
return QuestionType.RANK_ORDER;
} else if (questionTypeInfo instanceof PresentationHeaderQuestionTypeInfo) {
return QuestionType.PRESENTATION_HEADER;
} else if (questionTypeInfo instanceof PresentationHtmlQuestionTypeInfo) {
return QuestionType.PRESENTATION_HTML;
} else if (questionTypeInfo instanceof AutoIncrementQuestionTypeInfo) {
return QuestionType.AUTO_INCREMENT;
} else if (questionTypeInfo instanceof SingleChoiceQuestionTypeInfo) {
return QuestionType.SINGLE_CHOICE;
}

return null;
}

最佳答案

您可以按照其他人的建议使用 Map,但如果对您的情况有意义,我个人会使用委托(delegate)。在您的 QuestionTypeInfo 接口(interface)中,声明一个抽象方法 getQuestionType 返回 QuestionType 枚举的实例,并在其所有实现中使用适当的值覆盖它.

interface QuestionTypeInfo {
QuestionType getQuestionType();
}

enum OpenEndedTextQuestionTypeInfo implements QuestionTypeInfo {
@Override
public QuestionType getQuestionType() {
return QuestionType.OPEN_ENDED;
}
}

然后,在 parseQuestionType 方法中,只需使用:

private static QuestionType parseQuestionType(QuestionTypeInfo questionTypeInfo) {
return questionTypeInfo.getQuestionType();
}

关于java - 如果使用枚举,如何清理代码太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55809769/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com