枚举与接口常量、类常量有什么区别?

[复制链接]
发表于 2022-10-21 10:51:48 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
目录

  • 一个简单的需求

    • 接口常量
    • 类常量

  • 枚举

    • 什么是枚举?
    • 枚举常量
    • 限制输入的类型
    • 枚举可以使用==来比较吗?
    • 枚举实现单例


作者:小牛呼噜噜 | https://xiaoniuhululu.com
计算机内功、JAVA底层、面试相关资料等更多精彩文章在公众号「小牛呼噜噜 」
一个简单的需求

在我们实际开发java项目过程中,突然有一天"领导老王"给了个任务, 公司系统需要支持商品管理的需求
比如水果有:苹果,香蕉,葡萄等等,电子产品有:电脑,手机,摄像机等等
我们一般新建商品类Goods:
  1. public class Goods {
  2.     /**
  3.      * 商品名称
  4.      */
  5.     private String name;
  6.     /**
  7.      * 商品类型
  8.      */
  9.     private Integer type;
  10.     public Goods(String name, Integer type) {
  11.         this.name = name;
  12.         this.type = type;
  13.     }
  14.     public String getName() {
  15.         return name;
  16.     }
  17.     public void setName(String name) {
  18.         this.name = name;
  19.     }
  20.     public Integer getType() {
  21.         return type;
  22.     }
  23.     public void setType(Integer type) {
  24.         this.type = type;
  25.     }
  26. }
复制代码
然后我们就直接可以使用它:
  1. public class GoodsTest {
  2.     public static void main(String[] args) throws InterruptedException {
  3.         Goods goods = new Goods("水果",1);//1代表苹果,2:香蕉,3:葡萄
  4.         System.out.println(goods.getName());
  5.     }
  6. }
复制代码
但是有个问题,业务代码不清晰,有时候开发人员并不知道1、2、3代表什么意思,而且在业务代码层里面直接写数字或者字符串也是非常危险的时,我们需要一种方案,既能将相关的状态,类型放在一起,又可以限制类的输入值,提升项目的安全性
接口常量

我们可以使用接口常量来解决上面的问题
  1. public interface StatusContentFace {
  2.     public static final String fruit  = "fruit";
  3.     public static final Integer apple  = 1;
  4.     public static final Integer banana  = 2;
  5.     public static final Integer grape  = 3;
  6.     //==========================
  7.     public static final String eleProduct  = "eleProduct";
  8.     public static final Integer computer  = 101;
  9.     public static final Integer phone  = 102;
  10.     public static final Integer camera  = 103;
  11. }
复制代码
我们再来看下测试类:
  1. public class GoodsTest1 {
  2.     public static void main(String[] args) throws InterruptedException {
  3.         Goods goods = new Goods(StatusContentFace.fruit,StatusContentFace.apple);
  4.         Goods goods_2 = new Goods(StatusContentFace.eleProduct,StatusContentFace.computer);
  5.         System.out.println(goods.getName());
  6.         System.out.println(goods_2.getName());
  7.     }
  8. }
复制代码
这样能够让相关的常量都在同一个接口文件中,接口常量,写起来比较简洁,但是为了让其他人知道每个常量的含义,最好写上注释。
但它同时有个问题,由于java中接口是支持多继承的

  • 我们可以将内容深入到其实现类代码中,这样对于一个常量类接口来说显然是不合理。
  • 我们还可以在其子接口里继续添加常量,这样在祖先接口中就无法控制所有常量,这样无疑是非常危险的。
一般不建议用的,但接口常量也不是一无是处的,可以通过内部接口来实现分组效果
  1. public class GoodsTest2 {
  2.     public static void main(String[] args) throws InterruptedException {
  3.         Goods goods = new Goods(Fruit.type,Fruit.banana);
  4.         Goods goods_2 = new Goods(EleProduct.type,EleProduct.phone);
  5.         System.out.println(goods.getName());
  6.         System.out.println(goods_2.getName());
  7.     }
  8.    
  9.     //常量分组
  10.     public interface Fruit {
  11.         String type = "fruit";
  12.         Integer apple = 1;
  13.         Integer banana = 2;
  14.         Integer grape = 3;
  15.     }
  16.     public interface EleProduct {
  17.         String type = "eleProduct";
  18.         Integer computer = 101;
  19.         Integer phone = 102;
  20.         Integer camera = 103;
  21.     }
  22.    
  23. }
复制代码
这样我们可以把相关的常量都归为一类,更加简洁明了
类常量

我们一般常用的是类常量方式:
  1. public final class StatusConstant {
  2.     private StatusConstant() {} //防止该类实例化
  3.     public static final String fruit  = "fruit";
  4.     public static final Integer apple  = 1;
  5.     public static final Integer banana  = 2;
  6.     public static final Integer grape  = 3;
  7.     //==========================
  8.     public static final String eleProduct  = "eleProduct";
  9.     public static final Integer computer  = 101;
  10.     public static final Integer phone  = 102;
  11.     public static final Integer camera  = 103;
  12. }
复制代码
注意:一般用final关键字修饰 class 防止其被继承,并将其构造函数 private 化,防止被实例化
测试类:
  1. public class GoodsTest3 {
  2.     public static void main(String[] args) throws InterruptedException {
  3.         Goods goods = new Goods(StatusConstant.fruit, StatusConstant.banana);
  4.         Goods goods_2 = new Goods(StatusConstant.eleProduct, StatusConstant.phone);
  5.         System.out.println(goods.getName());
  6.         System.out.println(goods_2.getName());
  7.     }
  8. }
复制代码
我们可以发现类常量的方式,的确很方便,也没有接口常量多继承的烦恼。但是她所能承接的信息,维度不够,只能一个字段的去承接信息,然而当项目复杂的话,我们希望往往其能承接更多维度的信息,类似于对象一样,拥有更多的属性
  1. {
  2.     "name": ...,
  3.     "type": ...,
  4.      ...
  5. }
复制代码
这时候,我们本文的主角,枚举就闪亮登场了!

枚举

什么是枚举?

枚举是一种特殊的类,所有的枚举类都是Enum类的子类,就类似Object类一样,由于java类是单继承的,所以不能在继承其他类或者枚举了。
枚举变量不能使用其他的数据,只能使用枚举中常量赋值。能提高程序的安全性。
格式:
  1. public enum 枚举名{
  2.   //枚举的取值范围
  3. }
复制代码
枚举常量

我们先定义一个枚举类,来定义常量:
  1. public enum ContentEnums {
  2.     Apple(1,"苹果"),
  3.     Banana(2,"香蕉"),
  4.     Grape(3,"葡萄"),
  5.     Computer(101,"电脑"),
  6.     Phone(102,"手机"),
  7.     Camera(103,"摄像机"),
  8.    
  9.     Fruit(10010,"fruit"),
  10.     EleProduct(10020,"eleProduct");
  11.     private Integer code;
  12.     private String desc;
  13.     ContentEnums(Integer code, String desc) {
  14.         this.code = code;
  15.         this.desc = desc;
  16.     }
  17.     public Integer getCode() {
  18.         return code;
  19.     }
  20.     public void setCode(Integer code) {
  21.         this.code = code;
  22.     }
  23.     public String getDesc() {
  24.         return desc;
  25.     }
  26.     public void setDesc(String desc) {
  27.         this.desc = desc;
  28.     }
  29. }
复制代码
测试类:
  1. public class GoodsTest4 {
  2.     public static void main(String[] args) throws InterruptedException {
  3.         Goods goods = new Goods(ContentEnums.Fruit.getDesc(), ContentEnums.Apple.getCode());
  4.         Goods goods_2 = new Goods(ContentEnums.EleProduct.getDesc(), ContentEnums.Phone.getCode());
  5.         System.out.println(goods.getName());
  6.         System.out.println(goods_2.getName());
  7.     }
  8. }
复制代码
看到这大家可能就有疑问了,枚举和常量类相比,有什么优点吗?

  • 枚举其实是一种特殊的类,可以承接对象的多维信息,但是常量类往往只能承接字段,信息比较单一
  • 枚举可以搭配switch语句使用,来代替if/else
  1. ContentEnums content = ContentEnums.Apple;
  2. switch (content) {
  3.     case Apple:
  4.         System.out.println("苹果");
  5.         break;
  6.     case Banana:
  7.         System.out.println("香蕉");
  8.         break;
  9.     case Grape:
  10.         System.out.println("葡萄");
  11.         break;
  12.     default:
  13.         System.out.println("未找到匹配类型");
  14. }
复制代码

  • enum 有一个非常有趣的特性,它可以为enum实例编写方法
  1. public enum MethodEnums {
  2.     VERSION {
  3.         @Override
  4.         String getInfo() {
  5.             return System.getProperty("java.version");
  6.         }
  7.     },
  8.     DATE_TIME {
  9.         @Override
  10.         String getInfo() {
  11.             return
  12.                     DateFormat.getDateInstance()
  13.                             .format(new Date());
  14.         }
  15.     };
  16.     abstract String getInfo();
  17.     public static void main(String[] args) {
  18.         for(MethodEnums csm : values()) {
  19.             System.out.println(csm.getInfo());
  20.         }
  21.     }
  22. }
复制代码
结果:
1.8.0_271
2022-9-21
除了抽象方法,普通方法也是可以的,这里就不展示了

  • 网上还有其他一些优点,感觉没啥特别值得说的
限制输入的类型

我们可以通过枚举来将相关的状态,类型放在一起,文章一开头,但我们怎么才能限制类的输入值呢?其实很简单,别被绕进去,我们只需将输入类型 改为指定的枚举即可
我们改造一下Goods类:
  1. public class Goods {
  2.     /**
  3.      * 商品名称
  4.      */
  5.     private String name;
  6.     /**
  7.      * 商品类型
  8.      */
  9.     private Integer type;
  10. //    public Goods(String name, Integer type) {
  11. //        this.name = name;
  12. //        this.type = type;
  13. //    }
  14.     public Goods() {//防止外部实例化
  15.     }
  16.     public String getName() {
  17.         return name;
  18.     }
  19.     public void setName(String name) {
  20.         this.name = name;
  21.     }
  22.     public Integer getType() {
  23.         return type;
  24.     }
  25.     public void setType(Integer type) {
  26.         this.type = type;
  27.     }
  28.     public static Goods addGoods(ContentEnums enums){
  29.         Goods goods = new Goods();
  30.         goods.setName(enums.getDesc());
  31.         goods.setType(enums.getCode());
  32.         return goods;
  33.     }
  34. }
复制代码
测试类:
  1. public class GoodsTest5 {
  2.     public static void main(String[] args) throws InterruptedException {
  3.         Goods goods = Goods.addGoods(ContentEnums.Apple);
  4.         Goods goods_2 = Goods.addGoods(ContentEnums.Computer);
  5.         System.out.println(goods.getName());
  6.         System.out.println(goods_2.getName());
  7.     }
  8. }
复制代码
这样,我们就可以限制创建对象时的输入值类型了
枚举可以使用==来比较吗?

可以使用==来比较 enum 实例,编译器会自动为你提供equals()和 hashCode() 方法。Enum 类实现了 Comparable 接口,所以它具有 compareTo() 方法。同时,它还实现了 Serializable 接口。
枚举实现单例

枚举类型是天生线程安全的,并且只会装载一次,我们可以利用了枚举的这个特性来实现单例
  1. public enum SingleInstance {
  2.     INSTANCE;
  3.     public void funDo() {
  4.           System.out.println("doSomething");
  5.     }
  6. }
复制代码
使用方式:SingleInstance.INSTANCE.funDo()
这种方法充分 利用枚举的特性,让JVM来帮我们保证线程安全和单一实例的问题。写法也极其简洁。
参考:
《On Java 8》
《Effective java》第3版
本篇文章到这里就结束啦,很感谢你能看到最后,如果觉得文章对你有帮助,别忘记关注我!更多精彩的文章

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表