所谓有鬼 其实是人们心中有个鬼

让我帮你画个符吧

枚举想说爱你不容易。。

最近项目结束了。回顾回顾以前的代码。感觉有些需要重构 于是乎就翻天覆地的去找了些资料来学习.
For example
对于多条的if else语句就应该使用switch语句来进行替换,而对于常量的处理情况,选择的方法就很多

第一:java是通过在接口或者类中定义public static final 的变量来实现的。比如吧
public interface SharpShooter_1 {
    public static final int LOCKED = 1;     //锁定
    public static final int AIM = 2;        //瞄准
    public static final int SHOOT = 3;      //射击
}

那么我们调用的时候
public class TestDemo_1 {
    public static void main(String args[]) {
        TestDemo_1 test = new TestDemo_1();
        test.doAction(1);
        test.doAction(2);
        test.doAction(3);
        test.doAction(4);
    }

    /**
     * 执行的动作
     * @param action
     */
    public void doAction(int action) {
        switch (action) {
            case SharpShooter_1.LOCKED:
                System.out.println("1:锁定目标");
                break;
            case SharpShooter_1.AIM:
                System.out.println("2:瞄准目标");
                break;
            case SharpShooter_1.SHOOT:
                System.out.println("3:射击");
                break;
            default:
                System.out.println("×:游戏还没有定义此动作!");
        }
    }
}

但是这样我觉得不能完全达到见其名知其意.比如在main函数里面的        
    test.doAction(1);
        test.doAction(2);
        test.doAction(3);
        test.doAction(4);

让人家看以来就有点丈二和尚摸不到头脑的感觉。
[注意]:switch语句的条件只能接收数值或字符(byte、short、int或char)或枚举(enum)类型的变量名或表达式。如果没有符合 条件数值或字符,则执行default语句,default语句不是必须的,如果没有默认要处理的动作,则default语句可省略。break语句的作 用是跳出循环块。
于是再呼。枚举就粉墨登场了。

public enum SharpShooter_2 {
    LOCKED,
    AIM,
    SHOOT
}

public class TestDemo_2 {

    public static void main(String args[]){
        TestDemo_2 test=new TestDemo_2();
        test.doAction(SharpShooter_2.LOCKED);
        test.doAction(SharpShooter_2.AIM);
        test.doAction(SharpShooter_2.SHOOT);
    }
    /**
     * 执行的动作
     * @param action
     */
    public void doAction(SharpShooter_2 action) {
        switch (action) {
            case LOCKED:
                System.out.println("1:锁定目标");
                break;
            case AIM:
                System.out.println("2:瞄准目标");
                break;
            case SHOOT:
                System.out.println("3:射击");
                break;
            default:
                System.out.println("×:游戏还没有定义此动作!");
        }
    }
}

再看看这次的代码,是不是代码比上次的清晰了一些呢?

其实枚举说白了也是一个类 这个类继承自java.lang.Enum类 你去查阅jdk 他们默认都是public static final的。可以直接通过枚举类型名直接使用它们。
关于java.lang.Enum类我在这里不详细叙述。网络上有很多这样的文章.

posted on 2009-07-28 10:07  鬼话符  阅读(154)  评论(0)    收藏  举报

导航