什么是枚举,它们为什么有用? [英] What are enums and why are they useful?

查看:37
本文介绍了什么是枚举,它们为什么有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我浏览了这个网站上的一些问题,我发现提到了一个 enum 在单例模式中使用 关于此类解决方案的所谓线程安全优势.

Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread-safety benefits to such solution.

我从未使用过 enum 并且我已经使用 Java 编程超过两年了.显然,他们改变了很多.现在,他们甚至在自己内部全面支持 OOP.

I have never used enums and I have been programming in Java for more than a couple of years now. And apparently, they changed a lot. Now they even do full-blown support of OOP within themselves.

推荐答案

当变量(尤其是方法参数)只能从一小组可能的值中取出一个时,您应该始终使用枚举.例如类型常量(合同状态:永久"、临时"、学徒")或标志(立即执行"、推迟执行").

You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: "permanent", "temp", "apprentice"), or flags ("execute now", "defer execution").

如果您使用枚举而不是整数(或字符串代码),则会增加编译时检查并避免因传入无效常量而导致错误,并记录哪些值可以合法使用.

If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.

顺便说一句,过度使用枚举可能意味着您的方法做得太多(拥有多个单独的方法通常更好,而不是一个采用多个标志来修改其功能的方法),但是如果您必须使用标志或类型代码,枚举是要走的路.

BTW, overuse of enums might mean that your methods do too much (it's often better to have several separate methods, rather than one method that takes several flags which modify what it does), but if you have to use flags or type codes, enums are the way to go.

举个例子,哪个更好?

/** Counts number of foobangs.
 * @param type Type of foobangs to count. Can be 1=green foobangs,
 * 2=wrinkled foobangs, 3=sweet foobangs, 0=all types.
 * @return number of foobangs of type
 */
public int countFoobangs(int type)

对比

/** Types of foobangs. */
public enum FB_TYPE {
 GREEN, WRINKLED, SWEET, 
 /** special type for all types combined */
 ALL;
}

/** Counts number of foobangs.
 * @param type Type of foobangs to count
 * @return number of foobangs of type
 */
public int countFoobangs(FB_TYPE type)

方法调用如下:

int sweetFoobangCount = countFoobangs(3);

然后变成:

int sweetFoobangCount = countFoobangs(FB_TYPE.SWEET);

<小时>

在第二个示例中,可以立即明确允许哪些类型,文档和实现不能不同步,并且编译器可以强制执行此操作.此外,像


In the second example, it's immediately clear which types are allowed, docs and implementation cannot go out of sync, and the compiler can enforce this. Also, an invalid call like

int sweetFoobangCount = countFoobangs(99);

不再可能.

这篇关于什么是枚举,它们为什么有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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