JAVA enum实现简单状态机功能

来源:互联网 发布:永久域名发布 编辑:程序博客网 时间:2024/04/28 09:51

(转载请注明出处:http://blog.csdn.net/buptgshengod

1.背景

            我们做android应用,往往要进行多个状态的切换,就像是照相机功能的侦测,预置,拍照等状态。有的时候通过if else也能完成功能,但是却显得代码很乱,这时候用enum枚举方法产生状态机机制,就很清晰的实现功能。

2.代码

简单的三种状态切换

public class Main {    public enum Test{        ONE,TWO,THREE;    }    public static void main(String args[]){        CHANGE ob=new CHANGE();        for(int i=0;i<3;i++){            ob.change();        }   }    public static class CHANGE{        Test ts=Test.ONE;        public void change(){        switch(ts){            case ONE: ts=Test.TWO;                     System.out.println("this is test one");                     break;            case TWO: ts=Test.THREE;                      System.out.println("this is test two");                     break;            case THREE: ts=Test.ONE;                      System.out.println("this is test three");                     break;        }    }    }}

效果图


1 0
原创粉丝点击