How should I implement object comparisons in a flexible manner? For example, I have a Person class and sometimes I will compare based on name and sometimes I will compare based on age.

Ryan Breidenbach

Instead of having the Person class implement the Comparable interface, you could delegate the comparing to another class. Perhaps you could have a PersonComparator interface that you could implement for the various types of comparisons. For example:

public interface Person {
  public String getName();  
  public int getAge();
}

public interface PersonComparator {
  public int compare(Person p1, Person p2);
}

public class AgeComparator implements PersonComparator {
  public int compare(Person p1, Person p2) {
    if (p1.getAge() == p2.getAge()) return 0;
    return p1.getAge() > p2.getAge() ? 1 : -1;    
  }
}

public class NameComparator implements PersonComparator {
  public int compare(Person p1, Person p2) {
    return p1.getName().compareTo(p2.getName());
  }
}
This is a very simple example of the Strategy Pattern. This allows your comparisons and your object to change independent of one another.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact