Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enums to implement utility classes and singletons

Tags:

java

enums

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 :)

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)?

like image 900
Rich Avatar asked Feb 14 '11 13:02

Rich


People also ask

How would you implement Singleton using enum?

Singleton using Enum in Java: By default creation of the Enum instance is thread-safe, but any other Enum method is the programmer's responsibility. You can access it by EasySingleton. INSTANCE, far simpler than calling getInstance() function on Singleton.

Why enum is best for Singleton?

It is simple to write Enum Singletons. Enums are inherently serializable. No problems of reflection occur. It is thread-safe to create enum instances.

What is the point of using enums?

Enumerations make for clearer and more readable code, particularly when meaningful names are used. The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future.

Can enum implement abstract class?

Enum cannot extend any class in java,the reason is, by default Enum extends abstract base class java. lang. Enum. Since java does not support multiple inheritance for classes, Enum can not extend another class.


2 Answers

It would seem more intuitive to me to use enums for real enumerations.

like image 123
Brian Agnew Avatar answered Oct 22 '22 15:10

Brian Agnew


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.

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.

like image 21
ColinD Avatar answered Oct 22 '22 16:10

ColinD