Java Enum 属性最佳实践
我见过两种处理具有属性的枚举的方法。一个比另一个更好吗?
作为属性:
public enum SEARCH_ENGINE {
GOOGLE("http://www.google.com"),
BING("http://www.bing.com");
private final String url;
private SEARCH_ENGINE(String url) {
this.url = url;
}
public String getURL() {
return url;
}
}
作为方法:
public enum SEARCH_ENGINE {
GOOGLE {
public String getURL() {return "http://www.google.com";}
},
BING {
public String getURL() {return "http://www.bing.com";}
};
public abstract String getURL();
}
I've seen two approaches to handling enums with properties. Is one better than the other?
As a property:
public enum SEARCH_ENGINE {
GOOGLE("http://www.google.com"),
BING("http://www.bing.com");
private final String url;
private SEARCH_ENGINE(String url) {
this.url = url;
}
public String getURL() {
return url;
}
}
As a method:
public enum SEARCH_ENGINE {
GOOGLE {
public String getURL() {return "http://www.google.com";}
},
BING {
public String getURL() {return "http://www.bing.com";}
};
public abstract String getURL();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一个对我来说显然看起来更干净 - 它利用了枚举的每个元素都有一个在初始化时已知的固定字符串 URL 的共性。您在第二个版本的每个实现中有效地重复了该“逻辑”。您将重写一个方法,以在每种情况下提供相同的逻辑(“仅返回编译时已知的字符串”)。我更喜欢保留对行为变化的覆盖。
我建议在第一个中将
url
字段设为私有。The first clearly looks cleaner to me - it makes use of the commonality that each element of the enum will have a fixed String URL which is known at initialization. You're effectively repeating that "logic" in each implementation in the second version. You're overriding a method to provide the same logic ("just return a string which is known at compile-time") in each case. I prefer to reserve overriding for changes in behaviour.
I suggest making the
url
field private though, in the first.我会选择第一个,因为如果您忘记添加网址,编译器会抱怨。第二个会让你在这里犯错误。
I'd go with the first since the compiler complains if you somehow forget to add a url. The second would let you make errors here.
请查看 Josh Bloch 的《Effective Java》 本章中的第 21 项。它讨论了类型安全枚举模式。
Take a look at item 21 from this chapter of Josh Bloch's Effective Java. It talks about the type safe enum pattern.