Singleton of Java functional interface as enum

  • A+
Category:Languages

While looking at the source code of the Comparators class, I came across these lines of code.

class Comparators {      //...      enum NaturalOrderComparator implements Comparator<Comparable<Object>> {         INSTANCE;          @Override         public int compare(Comparable<Object> c1, Comparable<Object> c2) {             return c1.compareTo(c2);         }          @Override         public Comparator<Comparable<Object>> reversed() {             return Comparator.reverseOrder();         }     }      //...  } 

I think I understand what this does. It's a Singleton instance which implements the Comparator interface. It uses the "compareTo" of classes that implement the Comparable interface for natural ordering (please correct me if I am wrong in any of this).

What I do not understand however, why is it done using an enum. I really like enums for Singletons, don't get me wrong but in this case I personally think this would have been simpler:

public static final Comparator<Comparable<Object>> NATURAL_ORDER_COMPARATOR =     new Comparator<Comparable<Object>>() {         @Override         public int compare(Comparable<Object> c1, Comparable<Object> c2) {             return c1.compareTo(c2);         }          //...      } 

Are there any reasons to implement this using enums aside from personal preference?

 


I think it's because Serializable.

In your way, if someone create an object and hold the Comparators.NATURAL_ORDER_COMPARATOR. When he write the object and read it back, a new NATURAL_ORDER_COMPARATOR will be created. Since the object cost is so small but it break the singleton.

An evidence is Collections.ReverseComparator. It uses your pattern:

static final ReverseComparator REVERSE_ORDER = new ReverseComparator(); 

But the price is it must add the following code to maintain the singleton

private Object readResolve() { return Collections.reverseOrder(); } 

Now which one is easier? I think is the enum. Personnally, I prefer to use 'enum singleton' pattern as the first choice.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: