枚举公共接口
public interface IPairs<K, V, C extends Enum> {
/**
* 返回枚举对象
* */
C get();
/**
* 返回枚举项的 key
* */
K key();
/**
* 返回枚举项的 value
* */
V value();
}
状态枚举类
public enum StatusEnum implements IPairs<Integer, String, StatusEnum> {
DISABLED(0, "record has been disabled"),
ENABLED(1, "record has been enabled"),
DELETES(9, "record has been deleted")
;
private int code;
private String desc;
StatusEnum(int code, String desc) {
this.code = code;
this.desc = desc;
}
public StatusEnum get() {
return this;
}
@Override
public Integer key() {
return this.code;
}
@Override
public String value() {
return this.desc;
}
}
响应枚举类
public enum ResponseEnum implements IPairs<Integer, String, ResponseEnum> {
SUCCESS(10000, "success"),
FAILED(10001, "failed")
;
private int code;
private String desc;
ResponseEnum(int code, String desc) {
this.code = code;
this.desc = desc;
}
public ResponseEnum get() {
return this;
}
@Override
public Integer key() {
return this.code;
}
@Override
public String value() {
return this.desc;
}
}
代码验证
public class AnswerApp {
public static void main(String[] args) {
invoke(StatusEnum.ENABLED);
System.out.println();
response(ResponseEnum.SUCCESS);
}
private static void response(IPairs pairs) {
System.out.println(pairs.get() == ResponseEnum.SUCCESS);
System.out.println(MessageFormat.format("key: {0}, value: {1}", pairs.key(), pairs.value()));
}
private static void invoke(IPairs pairs) {
System.out.println(pairs.get() == StatusEnum.ENABLED);
System.out.println(MessageFormat.format("key: {0}, value: {1}", pairs.key(), pairs.value()));
}
}
程序运行结果
true
key: 1, value: record has been enabled
true
key: 10,000, value: success
结论
: 项目中使用同一接口管理枚举类, 在方法参数中使用接口而不是用具体的枚举对象作为入参, 可以一定程度上降低程序的耦合性