Skip to content

Instantly share code, notes, and snippets.

@john77eipe
Created April 16, 2017 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john77eipe/97b4deb06b30d32e4bd2cc8ecefc8c0b to your computer and use it in GitHub Desktop.
Save john77eipe/97b4deb06b30d32e4bd2cc8ecefc8c0b to your computer and use it in GitHub Desktop.
//Vendor's code
interface ConditionCheck {
public boolean check(Integer i);
}
class MathUtility {
public static int sum(List<Integer> list, ConditionCheck condition){
//ability to add is only here
int sum=0;
for(Integer i: list){
if(condition.check(i)){
sum=sum+i;
}
}
return sum;
}
//client creates list of Ints
List<Integer> listOfInts = new ArrayList<Integer>();
listOfInts.add(2);
listOfInts.add(3);
listOfInts.add(4);
//client creates reusuable objects that will do the filtering
ConditionCheck isEven = new ConditionCheck<Integer>(){
@Override
public boolean check(Integer i) {
return i%2==0;
}
};
//client calls Vendor provided function
int result = MathUtility.sum(listOfInts, isEven);
//client feels like creating another filter
final List<Integer> special = Arrays.asList(new Integer[]{2,3});
ConditionCheck isSpecial = new ConditionCheck(){
@Override
public boolean check(Integer i) {
return special.contains(i);
}
};
int result = MathUtility.sum(listOfInts, isSpecial);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment