JavaOmnibus
GoF Strategy
GoF pattern • Behavioral
GoFBehavioralJava example

Strategy solves a specific structural problem in the design.

Swap algorithms behind a stable interface.

Pattern overview

GoF pattern

Swap algorithms behind a stable interface.

Intent

Define a family of algorithms, encapsulate each one, and make them interchangeable.

Problem

A behavior varies by policy, but conditionals or subclasses are making the code rigid.

Solution

Move the varying logic into strategy implementations selected by context.

Fit and tradeoffs

FamilyGoF
CategoryBehavioral
Best used when
  • For pricing rules, sorting rules, validation policies, or runtime-pluggable behavior.
Tradeoffs
  • Adds indirection and object wiring.
  • Tiny strategies can become noisy if variability is insignificant.

Java example

This example is intentionally compact so the pattern shape stays easy to see.

interface PricingStrategy {
    Money price(Cart cart);
}

final class StandardPricing implements PricingStrategy {
    public Money price(Cart cart) { return cart.subtotal(); }
}

final class PremiumPricing implements PricingStrategy {
    public Money price(Cart cart) { return cart.subtotal().multiply(new BigDecimal("0.90")); }
}

Related pages

Keep exploring