Skip to content

Instantly share code, notes, and snippets.

@billyyarosh
Created June 5, 2012 18:59
Show Gist options
  • Save billyyarosh/2876990 to your computer and use it in GitHub Desktop.
Save billyyarosh/2876990 to your computer and use it in GitHub Desktop.
Example of using concrete strategies.
package com.keaplogik.examples.design.patterns.strategy;
import com.keaplogik.examples.model.animals.Animal;
import java.util.Comparator;
/**
* Holds concrete strategies for working with animal lists.
* @keaplogik
*/
public enum AnimalListStrategy {
INSTANCE;
private AnimalListStrategy(){}
public final Comparator vertebrayStrategyFunc = new Comparator<Animal>() {
@Override
public int compare(Animal firstAnimal, Animal secondAnimal) {
if (firstAnimal.isVertebrate()
== secondAnimal.isVertebrate()) {
return 0;
} else if (firstAnimal.isVertebrate()
|| secondAnimal.isVertebrate()) {
return 1;
} else {
return -1;
}
}
};
public final Comparator speciesStrategyFunc = new Comparator<Animal>() {
@Override
public int compare(Animal firstAnimal, Animal secondAnimal) {
//In this case we can use the inherited Comparable.compareTo
//method within the String class to ensure proper ascending order
return firstAnimal.getSpecies().
compareTo(secondAnimal.getSpecies());
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment