在 Java 中,枚举类可以包含接口类型的字段,并且可以在枚举常量中提供接口的具体实现。这种设计模式允许你为每个枚举常量关联不同的行为,而这些行为是通过接口定义的。
下面是一个例子,展示如何使用接口作为字段,并在枚举常量中实现接口的方法:
首先定义一个接口 Action
,它声明了一个方法 performAction()
:
public interface Action {
void performAction();
}
然后创建一个枚举 Command
,该枚举有一个类型为 Action
的字段,并且每个枚举常量都会提供这个接口的一个具体实现:
public enum Command {
START(new Action() {
@Override
public void performAction() {
System.out.println("Start command executed.");
}
}),
STOP(new Action() {
@Override
public void performAction() {
System.out.println("Stop command executed.");
}
}),
RESTART(new Action() {
@Override
public void performAction() {
System.out.println("Restart command executed.");
}
});
private final Action action;
Command(Action action) {
this.action = action;
}
public void execute() {
action.performAction();
}
}
在这个例子中,Command
枚举类有一个名为 action
的字段,其类型为 Action
接口。每个枚举常量(START, STOP, RESTART)
都传入了一个实现了Action
接口的对象给构造函数。这可以通过匿名内部类来完成,也可以使用 lambda
表达式(如果接口是函数式接口)或者方法引用。
你可以像这样调用枚举常量上的 execute
方法以执行与之关联的动作:
public class Main {
public static void main(String[] args) {
Command.START.execute(); // 输出: Start command executed.
Command.STOP.execute(); // 输出: Stop command executed.
Command.RESTART.execute(); // 输出: Restart command executed.
}
}
这种方法使得每个枚举常量都可以有自己独特的行为,同时保持了代码的简洁性和可读性。如果你的接口只有一个抽象方法,那么它是函数式接口,你可以使用lambda
表达式来简化代码:
public enum Command {
START(() -> System.out.println("Start command executed.")),
STOP(() -> System.out.println("Stop command executed.")),
RESTART(() -> System.out.println("Restart command executed."));
private final Action action;
Command(Action action) {
this.action = action;
}
public void execute() {
action.performAction();
}
}
这种方式更加简洁,特别是在接口只有一个方法的时候。