Strategy

Intent
Move each variant of the same calculation into its own class, all behind a shared contract, so you can pick one (or add new ones) without touching the code that uses them.
Application
Swap a pricing switch for one strategy per plan and let Spring inject them all into a Map.
PricingControllerLegacyPricingServiceAthlete

On the left, the athlete sends a packet labelled plan=ten-pack to PricingController, which calls LegacyPricingService, highlighted in red.

The diagram does not change: LegacyPricingService stays highlighted in red as the place you must edit for every new plan.

To the right of LegacyPricingService, the PricingStrategy interface appears, highlighted.

Around the interface, three blocks appear, monthly, ten-pack and drop-in, highlighted and joined to PricingStrategy with implementation arrows.

The Spring context platform appears under all the blocks. LegacyPricingService disappears and PricingService takes its place, highlighted along with the context and joined to the interface by an injection link.

The plan=ten-pack packet travels from the athlete to the controller and from the controller to PricingService; the ten-pack block is highlighted and a 240.00 € packet travels back from PricingService to the controller.

To the left of ten-pack, near the controller, the student block appears, highlighted and joined to PricingStrategy with an implementation arrow. The rest of the diagram is unchanged.

Only the DelegatingPasswordEncoder block remains inside the Spring context, highlighted; the athlete sends it a packet labelled {bcrypt}….

The full diagram: the athlete, the controller and PricingService inside the Spring context, joined to the PricingStrategy interface, which monthly, ten-pack, drop-in and student implement.

Step 1 of 9

A switch that keeps growing

Your box has a small Spring Boot API that works out what each athlete pays. Today someone asks about the ten-pack with 12 sessions: GET /api/pricing/quote?plan=ten-pack&sessions=12.

Today there are three plans:

  • monthly: 79.00 €, however much you train.
  • ten-pack: 120.00 € for every started block of 10 sessions.
  • drop-in: 15.00 € per session, for visitors.

All the pricing lives in LegacyPricingService, inside a switch on the plan name.

Step 2 of 9

Then the student discount shows up

The coach wants a student rate. Where does it go? Into the same switch, of course: one more case, one more return, and fingers crossed you don't break the ten-pack along the way.

Every new plan means opening, changing and retesting the whole class. If two people work on prices at the same time, you get to resolve conflicts in the same method.

Step 3 of 9

One contract for every plan

First, give a name to what all plans have in common: given a PricingRequest (plan and sessions), they return a Money.

That's the PricingStrategy interface. One method, nothing else. Whoever computes prices no longer needs to know how each plan is priced, only that something fulfils this contract.

Step 4 of 9

One class per plan

Each branch of the switch becomes a class implementing PricingStrategy: MonthlyPricing, TenPackPricing and DropInPricing.

Look at @Component("ten-pack"): the bean name is exactly the key that comes in the URL. That's no accident, and you'll put it to work in the next step.

The ten-pack logic is isolated and easy to read: with 12 sessions, Math.ceilDiv(12, 10) gives 2 blocks (it rounds up), so 2 × 120.00 €.

Step 5 of 9

Spring hands you every strategy

Now the Spring context comes in. PricingService replaces the old service and asks for a Map<String, PricingStrategy> in its constructor.

Nothing to register by hand: Spring finds every bean implementing the interface and gives them to you in that map, keyed by bean name. With a single constructor you don't even need @Autowired.

Step 6 of 9

One request, end to end

Same request as before: plan ten-pack, 12 sessions.

  1. The controller reads the parameters and builds a PricingRequest.
  2. PricingService calls strategies.get("ten-pack") and gets TenPackPricing.
  3. The strategy computes 2 blocks × 120.00 € and returns 240.00 €.

The service no longer decides anything: it looks up and delegates. If someone asks for a plan that doesn't exist, the map returns null, the service throws UnknownPlanException and the API answers 400.

Step 7 of 9

Adding student without touching anything

Back to the coach's request. This time the fix is a new class, full stop: StudentPricing, registered as @Component("student"), which takes 20 % off the monthly fee: 79.00 € becomes 63.20 €.

Neither the service nor the controller changes. At startup Spring finds the new bean and adds it to the map under the key student.

Step 8 of 9

Spring already does it for you

Chances are you already use this pattern without noticing. Spring Security's DelegatingPasswordEncoder stores each hash with a prefix naming the algorithm: {bcrypt}…, {noop}…, {pbkdf2}….

When checking a password, it reads that {id}, looks up the matching encoder in its internal map and hands the work over. It is exactly our Map<String, PricingStrategy>, only with hashing algorithms.

Step 9 of 9

Recap

You went from a switch that grew with every plan to this:

  • Context: PricingService, which receives the strategies and delegates.
  • Strategy: PricingStrategy, the contract.
  • ConcreteStrategy: one class per plan, registered with its key as the bean name.

And the most Spring part of all: you didn't write a single line to pick the strategy. The container builds the map for you.

Cheatsheet →

Code

LegacyPricingService.java

public Money quote(String plan, int sessions) {
    switch (plan) {
        case "monthly":
            return Money.eur("79.00");
        case "ten-pack":
            return Money.eur("120.00").times(Math.ceilDiv(sessions, 10));
        case "drop-in":
            return Money.eur("15.00").times(sessions);
        // student discount? yet another case here...
        default:
            throw new UnknownPlanException(plan);
    }
}

LegacyPricingService.java

public Money quote(String plan, int sessions) {
    switch (plan) {
        case "monthly":
            return Money.eur("79.00");
        case "ten-pack":
            return Money.eur("120.00").times(Math.ceilDiv(sessions, 10));
        case "drop-in":
            return Money.eur("15.00").times(sessions);
        // student discount? yet another case here...
        default:
            throw new UnknownPlanException(plan);
    }
}

PricingStrategy.java

public interface PricingStrategy {
    Money priceFor(PricingRequest request);
}

TenPackPricing.java

@Component("ten-pack")
public class TenPackPricing implements PricingStrategy {
    @Override
    public Money priceFor(PricingRequest request) {
        return Money.eur("120.00").times(Math.ceilDiv(request.sessions(), 10));
    }
}

PricingService.java

private final Map<String, PricingStrategy> strategies;

public PricingService(Map<String, PricingStrategy> strategies) {
    this.strategies = strategies;
}

public Money quote(PricingRequest request) {
    var strategy = strategies.get(request.plan());
    if (strategy == null) {
        throw new UnknownPlanException(request.plan());
    }
    return strategy.priceFor(request);
}

PricingController.java

@GetMapping("/quote")
public QuoteResponse quote(@RequestParam String plan, @RequestParam int sessions) {
    var price = pricing.quote(new PricingRequest(plan, sessions));
    return new QuoteResponse(plan, sessions, price.amount().toPlainString());
}

StudentPricing.java

@Component("student")
public class StudentPricing implements PricingStrategy {
    @Override
    public Money priceFor(PricingRequest request) {
        return Money.eur("79.00").percentOff(20);
    }
}

SpringDoesItTooTest.java

PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String hash = encoder.encode("wod-2026");
assertThat(hash).startsWith("{bcrypt}");
assertThat(encoder.matches("wod-2026", hash)).isTrue();
assertThat(encoder.matches("wod-2026", "{noop}wod-2026")).isTrue();

PricingService.java

private final Map<String, PricingStrategy> strategies;

public PricingService(Map<String, PricingStrategy> strategies) {
    this.strategies = strategies;
}

public Money quote(PricingRequest request) {
    var strategy = strategies.get(request.plan());
    if (strategy == null) {
        throw new UnknownPlanException(request.plan());
    }
    return strategy.priceFor(request);
}

Quiz

1. What does Spring inject into a constructor that takes a Map<String, PricingStrategy>?

2. You want to add the student plan. What do you have to change?

3. How is Strategy different from State?

4. How does DelegatingPasswordEncoder know which algorithm to use when checking a password?

Cheatsheet →

Run it