Implement Strategy in Java by separating the stable context from the interchangeable algorithm contract and making the choice explicit.
Strategy: A pattern that packages interchangeable behavior behind a shared contract so the caller or context can choose among alternatives explicitly.
The basic Java shape is straightforward.
1public interface PricingStrategy {
2 Money priceFor(Cart cart);
3}
Each strategy implements one pricing policy:
1public final class RegularPricing implements PricingStrategy {
2 @Override
3 public Money priceFor(Cart cart) {
4 return cart.subtotal();
5 }
6}
7
8public final class DiscountPricing implements PricingStrategy {
9 @Override
10 public Money priceFor(Cart cart) {
11 return cart.subtotal().multiply(0.9);
12 }
13}
The context owns stable workflow and delegates the variable part:
1public final class CheckoutService {
2 private final PricingStrategy pricing;
3
4 public CheckoutService(PricingStrategy pricing) {
5 this.pricing = pricing;
6 }
7
8 public Receipt checkout(Cart cart) {
9 Money total = pricing.priceFor(cart);
10 return new Receipt(total);
11 }
12}
Use Strategy when:
Do not build Strategy just because two tiny code paths exist. If behavior is unlikely to grow and a simple branch is clearer, the pattern may be unnecessary.
Strategy is strong when behavior choice is a first-class design decision, not when it is pattern nostalgia.