java 枚举类可以实现单例模式,
因为枚举类的构造方法必须是私有的。
枚举类常用使用方式
- public enum ActionEnum {
- add("添加", 0),
- delete("删除", 1),
- select("查询", 2),
- update("修改", 3),
- stop("停止", 4),
- restart("重启", 5),
- check("检查", 6),
- download("下载", 7),
- upload("上传", 8),
- login("登录", 9),
- logout("退出", 10),
- other("其他", 11);
- private final String value;
- private final int intVal;
-
- ActionEnum(String value, int intVal) {
- this.value = value;
- this.intVal = intVal;
- }
-
- public static String getNameByIntVal(int intVal) {
- for (ActionEnum operateType : values()) {
- if (operateType.intVal == intVal)
- return operateType.name();
- }
- return other.name();
- }
-
- public String getValue() {
- return value;
- }
-
- public int getIntVal() {
- return intVal;
- }
- }
在枚举类中定义抽象方法需要枚举类中的每个成员常量实现
- public enum HttpCode {
- SUCCEED{
- public String getHttpCode(){
- return "200";
- }
- },
- ERROR{
- public String getHttpCode(){
- return "404";
- }
- };
-
- public abstract String getHttpCode();//定义抽象方法
- }
为什么称为成员常量,并且需要对每个成员常量实现?
- public enum HttpCode{
- SUCCEED,ERROR;
- }
编译后的源码
- Class HttpCode{
- public static final SUCCEED = new HttpCode();
- public static final ERROR = new HttpCode();
- }
然后最上面的那种使用方式你就会理解为什么可以那么写了
举个例子ActionEnum编译后,这样写你就会看懂了
就是add成员常量指向了new ActionEnum("添加", 0);
然后ActionEnum里面有private ActionEnum(String value, int intVal)有参构造。所以通过get方法可以获取到,同理你也可以通过set方法修改值,但是实际开发中没必要修改值。
- class ActionEnum{
- public static final add = new ActionEnum("添加", 0);
- private final String value;
- private final int intVal;
- private ActionEnum(String value, int intVal) {
- this.value = value;
- this.intVal = intVal;
- }
- public String getValue() {
- return value;
- }
-
- public int getIntVal() {
- return intVal;
- }
- }
另外枚举类还有三个方法