Part 4 of 6 · 1 min read
Lambdas
A one-method interface can be a lambda.
FeeStrategy has one method, so Java lets a lambda stand in for a class. This is short for rules that are only a line or two.
lot.setStrategy(m -> m > 240 ? 200 : 50);
This rule charges 200 for stays over 240 minutes and 50 otherwise. checkout(300) returns 200 and checkout(30) returns 50. Registries work too. A Map<String, FeeStrategy> can map names from a settings file to strategies, so that configuration picks the rule and the code has no switch.
Use a named class when the rule is long, has its own state, or needs tests of its own. Use a lambda when it is short. Standard Java already uses strategy this way: Comparator is a strategy for ordering, and list.sort(comparator) is the context.
Check yourself:
1. What does checkout(300) return for the lambda?
2. Which Java interface is a well-known strategy?