接口 VS 枚举,如何管理常量?

你平时有哪种方式,管理常量呢?

  • public static final关键字
  • 接口:管理状态码或配置选项,需要在不同类中共享
  • 枚举:管理有限的常量集合,具有相关的信息提示或描述

1.public static final关键字?

public class Demo{
  public static fianl String RESULT_YES = "1";
  public static fianl String RESULT_NO = "0";
}

// 实例
public static class DemoServiceImpl{

  public static void main(String []arg){
    
    System.out.println(Demo.RESULT_YES);  // 执行结果:1
    
    System.out.println(Demo.RESULT_NO);   // 执行结果:0
  
  }
  
}

2.接口?

public class Demo{
  // public static fianl String RESULT_YES = "1";
  // public static fianl String RESULT_NO = "0";
  
  // 存储上报内容
  public interface Uplink{
    String HEARTBEAT = "01";
    String FLOW = "03";
  }
  
  // 存储反馈的内容
  public interface Downward{
    String HEARTBEAT_BACK = "02";
    String FLOW_BACK = "04";
  }
  
}


// 实例
public static class DemoServiceImpl{

  public static void main(String []arg){
  
    System.out.println(Demo.Uplink.HEARTBEAT);  // 执行结果:01
    System.out.println(Demo.Uplink.FLOW);   // 执行结果:03
  
    System.out.println(Demo.Downward.HEARTBEAT_BACK);  // 执行结果:02
    System.out.println(Demo.Downward.FLOW_BACK);   // 执行结果:04
  
  }
  
}

3.枚举?


public class Demo{
  public static fianl String RESULT_YES = "1";
  public static fianl String RESULT_NO = "0";
  
  public enum demo{
        YES(200, "执行成功"), ERROR_500(500, "程序内部执行错误"), ERROR_404(404, "请求超时");

        private final int code;
        private final String desc;

        demo(int code, String desc){
            this.code = code;
            this.desc = desc;
        }

        public int getCode(){
            return code;
        }

        public String getDesc(){
            return desc;
        }
    }
  
}


// 实例
public static class DemoServiceImpl{

  public static void main(String []arg){
    
    int code = demo.YES.getCode();
    System.out.println(code);
    
    String desc = demo.YES.getDesc();
    System.out.println(desc);
  }
  
}

这三种方法的使用场景是什么?

  1. public static final 是最常用的常量表示方式,可以用在任意场合;

  2. 接口:定义的常量,可供多个类共享;比如,我们可以通过该方法,实现对tcp协议上行/下行数据,进行分类管理;

  3. 枚举:像错误码,这种需要内容描述的,使用枚举实现;例如,错误类型500/ 404/ 200/ 503…(详见上文例子)

  • 16
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值