枚举 VS 类 VS 接口 [英] Enums VS Classes VS Interfaces

查看:34
本文介绍了枚举 VS 类 VS 接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个网站上阅读了很多关于常量使用的帖子.

I have been reading a lot of posts on this site regarding the usage of constants.

问题:我什么时候应该使用枚举作为常量,而不是使用类或接口.

Question: When should I use Enums for constants, vs using classes or interfaces.

我看到了我希望解决的 2 个关键情况.

I see 2 key situations I am looking to address.

示例:

  • 常用日志字符串
  • 容器引用,例如在WebSphere EAR 的

示例:

  • 员工对象的员工工资率

从我读过的所有内容来看,这是我认为我已经掌握的内容以及我正在寻找的意见.

From everything I have read this is what I think I have a grasp on and what I am looking for an opinion on.

对于情况 1:设计方法:使用最终类和静态导入.
在这里看到:接口常量有什么用?

For situation 1: Design Approach: Use a final class and a static import.
Seen here: What is the use of interface constants?

对于情况 2:设计方法:应用枚举的使用将这些常量表示为一个对象.

For Situation 2: Design Approach: Apply the use of Enums to represent those constants as a object.

要记住的其他要点:

  • 如果常量字符串属于类,而您只需要将字符串值保留在使用它的类中
  • 不要在情况​​ 1 中使用接口.如上面的链接中提到的常量接口反模式..

预先感谢您的想法和意见.

Thanks in advance for thoughts and opinions.

推荐答案

全局常量实际上应该放在属性文件中,因为它允许每个应用程序单独配置它们而无需修改代码.对于特定于对象的常量,我关于 Enumstatic final 的一般经验法则我通常倾向于有多少元素以及这些元素的相关性.如果它们之间存在很大的关系,例如一副 Cards 中的 Suits,那么我会选择枚举.如果它是用户的默认年龄,那么这将成为最终的,因为没有目的将其设为枚举,因为它不需要在许多领域被引用.这些只是我对每种方法的一些想法.

Global constants as you put it should actually be in a properties file as it allows each application to configure them individually without a code modification. For object specific constants my general rule of thumb on Enum versus static final I typically lean towards how many elements there are to have and how related those elements are. If there is a big relation between them such as Suits in a deck of Cards then I would go for the enum. If it is default age for a user, then this becomes a final as there is no purpose to making it an enum as it would not need to be referenced in many areas. These are just some thoughts on each of the ways I have approached it.

这篇关于枚举 VS 类 VS 接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆