Strategy pattern with Lambda in Java

import java.util.Arrays; import java.util.List; public class TaxStrategyMainWithLambda { public static void main(String [] args) { //Create a List of Tax strategies for different scenarios with inline logic using Lambda List<TaxStrategy> taxStrategyList = Arrays.asList( (income) -> { System.out.println("PersonalTax"); return 0.30 * income; }, (income) -> { System.out.println("PersonalTaxWithPenalty"); return 0.40 * income; }, (income) -> { System.out.println("PersonalTaxWithRebate"); return 0.20 * income; } ); //Calculate Tax for different scenarios with corresponding strategies taxStrategyList.forEach((strategy) -> System.out.println(strategy.calculateTax(30000.0))); } }
This snippet clearly demonstrates how different tax rates can be calculated by using appropriate concrete strategy class.

I have tried to combine all the concrete strategy (algorithms) in a list and then access them by iterating over the list.

We can see that use of lambda expressions, makes the additional classes for concrete strategies redundant. You don’t need additional classes; simply specify additional behavior using lambda expression.

#java #lambda #strategy #pattern


Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.