Syed Sayem blog

Strategy pattern using Lambda

Strategy pattern example using Java 8 lambda

@FunctionalInterface
public interface Strategy<T> {
T compute(T x, T y);
}
public enum Operation implements Strategy<Double> {

ADD((x, y) -> x + y),
SUBTRACT((x, y) -> x - y),
MULTIPLY((x, y) -> x * y),
DIVIDE((x, y) -> x / y),
MAX(Double::max);

private Strategy<Double> strategy;

Operation(final Strategy<Double> strategy) {
this.strategy = strategy;
}

@Override
public Double compute(Double x, Double y) {
return strategy.compute(x, y);
}
}
public class App {

@Test
public void addition() {
Assert.assertEquals(10.0, Operation.ADD.compute(5d, 5d));
}

@Test
public void subtraction() {
Assert.assertEquals(0.0, Operation.SUBTRACT.compute(5d, 5d));
}

@Test
public void multiplication() {
Assert.assertEquals(25.0, Operation.MULTIPLY.compute(5d, 5d));
}

@Test
public void division() {
Assert.assertEquals(1.0, Operation.DIVIDE.compute(5d, 5d));
}
}
comments powered by Disqus