关于枚举,很多地方都会使用,简单来说就是定义了一组常量,并且这些常量存在着一些关联,他们描述的是一类常量.例如:
enum Color {
red, blue
}
但我更愿意把枚举看做是一种存储方式,它定义了一些数据,这些数据不需要从数据库里面读取,因为它们是确定的,已知的.在游戏开发过程中,这类数据经常被使用到.
/**
* 怪物类型
*
* @author Jason
*/
public enum MonsterType {
NPC(1, true, true),
DOOR(2, false, false),
BOX(3, false, false),;
private final int type;//类型
private final boolean canMove;//是否可以移动
private final boolean canAttack;//是否可以攻击
private MonsterType(int type, boolean canMove, boolean canAttack) {
this.type = type;
this.canMove = canMove;
this.canAttack = canAttack;
}
public final static MonsterType valueOf(int type) throws Exception {//传入类型 获取数据
for (MonsterType mt : MonsterType.values()) {
if (mt.type == type) {
return mt;
}
}
throw new Exception("参数类型错误:" + type);
}
public int getType() {
return type;
}
public boolean isCanMove() {
return canMove;
}
public boolean isCanAttack() {
return canAttack;
}
}
调用:
public static void main(String[] args) throws Exception {
MonsterType mt = MonsterType.valueOf(1);
System.out.println("类型:" + mt.getType() + ",是否可以移动:" + mt.isCanMove() + ",是否可以攻击:" + mt.isCanAttack());
}
枚举定义的常量使用起来非常方便快捷高效.