demo:
/**
* 2018年10月16日下午6:12:20
*/
package testenum;
/**
* @author XWF
*
*/
public class TestEnumChain {
/**
* @param args
*/
public static void main(String[] args) {
ENUM_CHAIN.doHandle(-2);
System.out.println("=======================");
ENUM_CHAIN.doHandle(23);
System.out.println("=======================");
ENUM_CHAIN.doHandle(44);
System.out.println("=======================");
ENUM_CHAIN.doHandle(90);
System.out.println("=======================");
ENUM_CHAIN.doHandle(222);
}
}
enum ENUM_CHAIN{
YOUNG("young") {
@Override
public boolean handle(int age) {
if(age>=0 && age<30) {
System.out.println(YOUNG.str+" "+age);
return true;
}else {
System.out.println(" not "+YOUNG.str);
return false;
}
}
},
MIDDLE("middle") {
@Override
public boolean handle(int age) {
if(age>=30 && age<60) {
System.out.println(MIDDLE.str+" "+age);
return true;
}else {
System.out.println(" not "+MIDDLE.str);
return false;
}
}
},
OLD("old") {
@Override
public boolean handle(int age) {
if(age>=60 && age<150) {
System.out.println(OLD.str+" "+age);
return true;
}else {
System.out.println(" not "+OLD.str);
return false;
}
}
},
ERR("err") {
@Override
public boolean handle(int age) {
System.out.println(ERR.str+">>>"+age);
return true;
}
};
private String str;
ENUM_CHAIN(String str){
this.str = str;
}
public abstract boolean handle(int age);
public static void doHandle(int x) {
for(ENUM_CHAIN ch:ENUM_CHAIN.values()) {
if(ch.handle(x)) {
return ;
}
}
}
}
结果: