Design patterns

patterns21StrategyPattern

Path
pkg8patterns/patterns21StrategyPattern.java
Package
pkg8patterns
Study order
21
Run
Single-file source launch
Command
java pkg8patterns/patterns21StrategyPattern.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg8patterns/patterns21StrategyPattern.java
1package pkg8patterns;2 3/*4 * Strategy (Behavioral)5 * ---------------------6 * INTENT: define a family of algorithms, encapsulate each, and make them7 *         interchangeable at runtime.8 * UML: Context --> Strategy ; concrete strategies implement the algorithm.9 * PROS: swap algorithms at runtime; removes conditionals; open/closed.10 * CONS: clients must know the strategies; many small classes (lambdas help).11 * REAL-WORLD: Comparator, payment methods, compression/encryption choices.12 */13import java.util.*;14import java.util.function.*;15 16public class patterns21StrategyPattern {17 18    // Strategy is just a function here (lambdas make this elegant)19    static int[] sortWith(int[] data, Comparator<Integer> strategy) {20        Integer[] boxed = Arrays.stream(data).boxed().toArray(Integer[]::new);21        Arrays.sort(boxed, strategy);22        return Arrays.stream(boxed).mapToInt(Integer::intValue).toArray();23    }24 25    interface PaymentStrategy { String pay(double amount); }26 27    public static void main(String[] args) {28        int[] data = {5, 2, 8, 1, 9};29        System.out.println("asc:  " + Arrays.toString(sortWith(data, Comparator.naturalOrder())));30        System.out.println("desc: " + Arrays.toString(sortWith(data, Comparator.reverseOrder())));31 32        // Interchangeable payment strategies33        Map<String, PaymentStrategy> strategies = Map.of(34                "card", amt -> "Paid $" + amt + " by credit card",35                "upi",  amt -> "Paid $" + amt + " via UPI",36                "cash", amt -> "Paid $" + amt + " in cash");37        for (String method : List.of("card", "upi", "cash"))38            System.out.println(strategies.get(method).pay(42.0));39    }40}