如何改进这个内部枚举代码?
我有这样的构造:
public class Constants {
enum SystemA implements Marker {
ConstOne(1), ConstTwo(2), ConstThree(3);
SystemA(int i)
{
number = i;
}
int number;
}
enum SystemB implements Marker {
ConstFour(4), ConstFive(5), ConstSix(6);
SystemB(int i)
{
number =i;
}
int number;
}
}
我有 Marker
所以我可以传递给这样的方法: method(Constants.SystemA)
或 method(Constants.SystemB)
列出所有枚举值的最佳方法是什么?我还想确保它不会重复任何枚举中的数字。
I have this construct:
public class Constants {
enum SystemA implements Marker {
ConstOne(1), ConstTwo(2), ConstThree(3);
SystemA(int i)
{
number = i;
}
int number;
}
enum SystemB implements Marker {
ConstFour(4), ConstFive(5), ConstSix(6);
SystemB(int i)
{
number =i;
}
int number;
}
}
I have Marker
so I can pass to method like this:method(Constants.SystemA)
or method(Constants.SystemB)
What is the best way to list all the enum values? I also want to make sure that it is not duplicating the number in any of the enums.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果两个枚举的约定相同,则可以将其合并为一个枚举。
但是,为了区分这两个系统,您可以有一个单独的“SystemType”枚举,其中包含 A、B...,并且您可以为 System 枚举中的每个常量分配一个 SystemType。
此外,您的 SystemType 枚举可以提供一个实例方法,该方法将返回给定类型的所有系统,以便您可以根据需要仅迭代该子集。
至于编号,如果序列像您的示例中一样简单,您可以使用枚举常量的 ordinal() 方法,以便您只需依赖常量声明顺序(可能添加一些数学)。我的意思是:
如果您确实需要为不同的系统类型定义不同的契约(仅对 SystemX 或其他有意义的方法),这当然是无用的。
附:
当然,
System
是一个非常糟糕的名字,因为它隐藏了java.lang.System
类。If the contract of the two enums is the same, you can have it into one single enum.
However, in order to distinguish the two systems, you can have a separate "SystemType" enum that will contain A, B, ... and you can assign a SystemType to each constant in your System enum.
Furthermore, your SystemType enum can provide an instance method that will return all the systems for a given type, so that you can iterate through only that subset as needed.
As for the numbering, if the sequence is as simple as in your example, you can make use of the ordinal() method of the enum constants so that you'll simply rely on the constant declaration order (perhaps with some math added). Here's what I mean:
This is of course useless if you really need to define different contracts for the different system types (methods that only make sense for SystemX or whatever).
P.S.:
Of course,
System
is a really bad name, as it hides thejava.lang.System
class.由于您在代码中声明所有枚举,因此您有责任提供不重叠的数字(如果需要)。
更有趣的问题是:为什么需要这个?听起来好像您正在将枚举用于它们并非设计用途的东西。
Since you are declaring all enums in code, it is your responsibility to provide non-overlapping numbers, if you need this.
The more interesting question is: Why would you need this? It smells like you are using enums for things they weren't designed for.
我将依赖一个类 - 一个工厂类 - 来创建和控制系统类的实例。
I would rely on one class - a factory class - to create and control the instances of your System classes.