Created
April 16, 2017 13:42
-
-
Save john77eipe/97b4deb06b30d32e4bd2cc8ecefc8c0b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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