Strategy Design Patterns
We can easily create a strategy design pattern using lambda.
To implement this pattern we will be using Interfaces and classes. The interface declares a behaviour and concrete classes define the behaviour.
If we want to introduce a new behaviour to the design, we need to add a new concrete class. So this implementation ends up with tons of concrete classes.
Example
Consider list of numbers numbers = (1,2,3,4,5,6,7,8,9,10). The requirement is to find the sum of all numbers.
- We will introduce an Interface Strategy and add an abstract method int sum(List<Integer> numbers)
public interface Strategy
public int sum(List<Integer> numbers);
}
Then we will add a concrete class which will define the behaviour
import java.util.List
public class SummAll implements Strategy {
@Override
public int sum(List<Integer> numbers) {
int sum = 0;
for (Integer num : numbers) {
sum = sum+num;
}
return sum;
}
}
2. Now if we get a new requirement to get a sum of all even numbers then we need to add a new concrete class and need to define behaviour to get a sum of all even numbers.
import java.util.List
public class SummAllEven implements Strategy {
@Override
public int sum(List<Integer> numbers) {
int sum = 0;
for (Integer num : numbers) {
if (num % 2 == 0) {
sum = sum + num;
}
}
return sum;
}
}
For each such requirement, we need to add a new concrete class and this will end up with a lot of classes.
Using Lambda we can solve this problem very easily, let us implement the Strategy Pattern using Lambda.
Strategy Patterns using Lambda
import java.util.Arrays
import java.util.List;
import java.util.function.Predicate;
public class StrategyPatternWithLambda {
public static int sum(final List<Integer> numbers, final Predicate<Integer> selector) {
return numbers.stream()
.filter(selector)
.mapToInt(Integer::valueOf)
.sum();
}
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
//Sum of all numbers
int sumALl = sum(numbers,e->true);
//Sum of all even numbers
int sumALlEven = sum(numbers,e->e%2==0);
//Sum of all odd numbers
int sumALlOdd = sum(numbers,e->e%2!=0);
//Sum of all numbers greater thann 4
int sumGt4 = sum(numbers,e->e>4);
}
}