使用枚举来实现实用程序类和单例 [英] Using enums to implement utility classes and singletons

查看:112
本文介绍了使用枚举来实现实用程序类和单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

彼得·劳瑞写道:大多数人忘记的枚举的两个使用在他的博客上。

Peter Lawrey writes about Two Uses of Enums that most people forget on his blog.

首先,我没有忘记 - 我甚至没有意识到:)

First of all, I hadn't forgotten - I hadn't even realised :)

这些方法很好,简洁 - 有什么好处除了简洁之外,与更传统的实现相同方式的方式相比,例如使用 final 类与 private 构造函数实用程序类?

These approaches are nice and concise - are there any benefits other than conciseness compared with the more traditional ways of achieving the same thing, such as using final classes with private constructors for utility classes?

另外还有什么问题(除了不期待的程序员混乱)?

Also, are there any issues (apart from confusing programmers who aren't expecting it)?

推荐答案

我不太同意该帖子首次使用枚举。如果你想要一个不可修改的实用程序类,只需给它一个私有构造函数。这很简单,而枚举在我看到的这种情况下没有额外的好处。

I don't really agree with the first use of an enum from that post. If you want an uninstantiable utility class, just give it a private constructor. It's that simple, and the enum provides no added benefit in that situation that I see.

使用枚举对于实用程序类中的单例是好的,但是我通常会尝试保持一个枚举被用于内部实现细节的事实。参见例如,Guava的谓词使用枚举执行某个谓词像 alwaysTrue()。它不会向用户公开枚举

The use of enums for singletons in utility classes is great, but I would generally try to keep the fact that an enum is being used an internal implementation detail. See, for example, Guava's Predicates class which uses an enum to enforce a single instance of certain Predicates like alwaysTrue(). It does not expose the enum to users though.

就其他好处而言:是的,还有其他好处例如内置的可串行化,并且绝对执行每个类加载器的枚举单个实例常量,即使反序列化。

As far as other benefits: yes, there are other benefits such as built-in serializability and absolutely enforcing a single instance of an enum constant per classloader, even when deserializing.

这篇关于使用枚举来实现实用程序类和单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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