我有一个接口(interface),我想用枚举来实现它,但是有些方法是相同的,这会导致代码重复。我会使用抽象类而不是接口(interface),但 java 不允许枚举扩展任何东西。有没有解决的办法?我包含了一些代码来帮助理解问题。
public interface CommandI {
boolean isCommand(String command);
void execute(Drawer drawer, Creature creature);
String getDescription();
}
public enum Command2 implements CommandI {
FORWARD{
private String description = "qwersadd";
private String[] aliases = {"fd", "forward"};
@Override
public boolean isCommand(String command) {
for (String s: aliases){
if (s.equals(command)){
return true;
}
}
return false;
}
@Override
public void execute(Drawer drawer, Creature creature) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getDescription() {
return description;
}
},
PENUP{
private String description = "vcvzxcvz";
private String[] aliases = {"pu", "penup"};
@Override
public boolean isCommand(String command) {
for (String s: aliases){
if (s.equals(command)){
return true;
}
}
return false;
}
@Override
public void execute(Drawer drawer, Creature creature) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getDescription() {
return description;
}
}
}
如您所见,只有执行方法不同。
最佳答案
我不确定您是否真的了解枚举的用途。以下是您应该实现 Command2
的方式:
public enum Command2 implements CommandI {
FORWARD("qwersadd", new String[] { "fd", "forward" }),
PENUP("vcvzxcvz", new String[] { "pu", "penup" });
private final String description;
private final String[] aliases;
private Command2(String description, String[] aliases) {
this.description = description;
this.aliases = aliases;
}
@Override
public boolean isCommand(String command) {
for (String s : aliases) {
if (s.equals(command)) {
return true;
}
}
return false;
}
@Override
public void execute(Drawer drawer, Creature creature) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getDescription() {
return description;
}
}
例如,当你想要实现 FORWARD
的 execute
主体时,只需(覆盖)覆盖它,如下所示:
FORWARD("qwersadd", new String[] { "fd", "forward" }) {
@Override
public void execute(Drawer drawer, Creature creature) {
// specific execute body for FORWARD
}
}
关于java - 摆脱枚举中的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23511047/