0

So I have this small bit of code

import java.util.Comparator;
public class PersonFullNameComparator implements Comparator<Person> {
    @Override
    public int compare(Person arg0, Person arg1) {
        return arg0.getFullName().compareTo(arg1.getFullName());
    }
}

I was reading about singletons earlier and don't quite get it, I am not sure where to go or start.

So how would I make this a singleton? Just this class.

Edit: It's just for practice, not doing anything very practical with it. More curiosity due to examples unlike it.

Austin
  • 11
  • 3

1 Answers1

0

As MadProgrammer already said, you don't really need it. The comparator is ver light weight, so there would be no problem creating it whenever you need it.

But because your class is so light weight and it is thread safe (no instance state at all), there is no harm in creating a singleton. Also it is very simple:

import java.util.Comparator;
public class PersonFullNameComparator implements Comparator<Person> {
  // This is your singleton
  public static final PersonFullNameComparator INSTANCE = new PersonFullNameComparator(); 

  // This is, if you want to forbid creating other instances
  private PersonFullNameComparator() {}

  @Override
  public int compare(Person arg0, Person arg1) {
    return arg0.getFullName().compareTo(arg1.getFullName());
  }
}
Gregor Raýman
  • 3,051
  • 13
  • 19