gpt4 book ai didi

java - 需要枚举设计指导

转载 作者:行者123 更新时间:2023-12-02 00:05:23 28 4
gpt4 key购买 nike

我真的很喜欢在编码时轻松阅读枚举。最近我遇到了一个任务,我需要接受一个关键字列表,并且每个关键字都会执行一个操作。

关键字示例:早餐、午餐、晚餐

所以我希望能够写出这样的东西:String WhatImGoingToMake = keywords.BREAKFAST("banana").getPopularRecipe();这里的想法是获取以香蕉为成分的流行早餐食谱。我想到这一点是因为我认为使用反射应该能够工作。

问题是我无法调用 getPopularRecipe(),因为它不是静态的,并且不允许用于内部类。

我是否正确,强制枚举做这样的事情并使用类代替并不常见?对于下一个编码员来说,最简单的实现是什么?

也许是因为现在已经很晚了,但我现在正在努力。

如果可能的话,我会尽量避免使用一长串 IF 语句或 switch 语句。我只是不喜欢看到他们,并且不惜一切代价避开他们。所以我不想写这样的东西:



if (param.equals("BREAKFAST") {
//lookup in breakfast db
} else if (param.equals("LUNCH") {
//you get the idea - I dont like this since it can go on forever if we start adding BRUNCH, SUPPER, SNACK
}

这是我有兴趣开始工作的枚举:



public enum MyUtil {
BREAKFAST {
public String getPopularRecipe(String ingredient) {
//do something with ingredient
return recipe;
}
},
LUNCH {
public String getPopularRecipe(String ingredient) {
//do something with ingredient
return recipe;
}
}
}

最佳答案

如果我正确理解你的问题,你需要在 Enum 中有一个 abstract 方法 getPopularRecipe() ,并且所有枚举实例都应该重写。

示例:

public enum MyUtil {
BREAKFAST {
@Override
public String getPopularRecipe(String ingredient) {
//do something with ingredient
return recipe;
}
},
LUNCH {
@Override
public String getPopularRecipe(String ingredient) {
//do something with ingredient
return recipe;
}
}
public abstract String getPopularRecipe(String ingredient);
}

查看此tutorial了解更多信息(阅读至最后)。

关于java - 需要枚举设计指导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14000009/

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