Java – implements utility classes and singletons using enumerations

Peter Lawley wrote about two uses of enums that most people forget on his blog

First, I didn't forget – I didn't even realize:)

These methods are concise and clear – what are the benefits of simplicity over more traditional methods that implement the same method, such as using a final class with a private constructor to implement a utility class?

In addition, is there any problem (except that confusing programmers don't expect it)?

Solution

I really don't agree with the first use of enum in this post If you want a non - instantiatable utility class, just give it a private constructor It's that simple. In the case I see, enumeration provides no additional benefits

It's good to use enums for singletons in utility classes, but I usually try to keep enums used as internal implementation details For example, see guava's predictions class, which uses enumeration to enforce a single instance of certain predicates, such as alwaystrue() But it does not expose enumerations to users

As for other benefits: Yes, there are other benefits, such as built-in serialization, and each class loader absolutely enforces a single instance of enumeration constants, even when deserialized

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>