sebastiandaschner blog


Strategy Pattern with CDI and lambdas

#java #javaee tuesday, april 10, 2018

The strategy design pattern dynamically chooses an implementation algorithm, a strategy, at runtime. The pattern can be used to select different business algorithms depending on the circumstances.

We could define different algorithm implementations as separate classes. Or we make use of Java SE 8 lambdas and functions, that serve as lightweight strategy implementation here.

CDI is capable of injecting parameterized types:

public class Greeter {

    @Inject
    Function<String, String> greetingStrategy;

    public String greet(String name) {
        return greetingStrategy.apply(name);
    }
}

A CDI producer creates and exposes the greeting depending on the dynamic logic. The actual strategy is represented by the Function type and being selected dynamically:

public class GreetingStrategyExposer {

    private final Function<String, String> formalGreeting = name -> "Dear " + name;
    private final Function<String, String> informalGreeting = name -> "Hey " + name;

    @Produces
    public Function<String, String> exposeStrategy() {
        // select a strategy
        ...
        return strategy;
    }
}

This post was reposted from my newsletter issue 020.

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: