VOOZH about

URL: https://www.javacodegeeks.com/2018/04/strategy-pattern-with-cdi-and-lambdas.html

⇱ Strategy Pattern with CDI and lambdas - Java Code Geeks


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;
 }
}
Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: Strategy Pattern with CDI and lambdas

Opinions expressed by Java Code Geeks contributors are their own.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

Tags
CDI
👁 Photo of Sebastian Daschner
Sebastian Daschner
April 11th, 2018Last Updated: April 11th, 2018
0 130 1 minute read

Sebastian Daschner

Sebastian Daschner is a self-employed Java consultant and trainer. He is the author of the book 'Architecting Modern Java EE Applications'. Sebastian is a Java Champion, Oracle Developer Champion and JavaOne Rockstar.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz