Behavioral Design Pattern
Strategy Design Pattern in Java
Define interchangeable algorithms and select the appropriate one at runtime.
In this lesson: Strategy encapsulates a family of algorithms behind a common interface. The context can switch strategies without changing its workflow.
Overview
Strategy is useful when its recurring design problem appears in a real application. It keeps the relevant responsibilities organized while allowing surrounding code to depend on clear abstractions.
Implementation
interface PricingStrategy { double price(double amount); }
final class RegularPricing implements PricingStrategy { public double price(double amount) { return amount; } }
final class DiscountPricing implements PricingStrategy { public double price(double amount) { return amount * .9; } }
final class Checkout { private final PricingStrategy strategy; Checkout(PricingStrategy strategy) { this.strategy = strategy; } double total(double amount) { return strategy.price(amount); } }
System.out.println(new Checkout(new DiscountPricing()).total(100));
When should you use it?
Use Strategy for pricing rules, validation policies, sorting, payment selection, compression, and algorithms that vary independently.
Next step: Continue with the Design Patterns course and explore the next pattern.