用Lambda简化枚举

需求场景

解释器需要能够解释执行一些预设的指令,为了避免字符串判断+switch/case的丑陋写法,选择使用枚举类实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Operation.java
public enum Operation {
op1 ("op1") {
public void exec () {
//...
}
},
op2 ("op2") {
public void exec () {
//...
}
};

private String type;
Operation(String type) { this.type = type; }

abstract public Data exec ();
}

用Lambda改写

使用Lambda需要一个只有一个抽象函数的接口

1
2
3
4
// Executable.java
public interface Executable {
void exec (Parser parser);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// MOperation.java
public enum MOperation implements Executable {
op1("op1", (Parser parser) -> {
//...
}),
op2("op2", (Parser parser) -> {
//...
});

private final String type;
private final Executable executor;
MOperation(String type, Executable executor) {
this.type = type;
this.executor = executor;
}

@Override
public Token exec (Parser parser) throws Exception {
return executor.exec(parser);
}
}

改写之后,不仅枚举部分的代码更简洁直观,而且可以通过executor传参,比之前更灵活


参考资料

java - Lambdas in the classical Operation enum example - Stack Overflow