Strategy and Template Method in Java and Spring: From an SLA if-Ladder to Policy Beans, a Lambda Map, a Sealed Switch and an Import Skeleton
SlaDesk answers one question, how many hours until the first response, for basic, pro and enterprise plans. The if-ladder works until a fourth plan arrives. As Strategy beans in an injected Map, adding premium is one new class and T-104 goes from 'Unknown plan: premium' to 1h. Then a final run() method imports CSV and pipe files with one shared skeleton.
What you will learn
- See the change cost of an if-ladder when a new plan arrives
- Implement Strategy as Spring beans looked up from an injected Map by bean name
- Choose between Strategy beans, a lambda map and a sealed interface with an exhaustive switch
- Fix the order of steps with a final Template Method and leave one step to subclasses
Before you start
- Java interfaces and abstract classes
- Spring beans and constructor injection
Strategy is for when the caller asks one question and the answer depends on something else, such as a customer's plan. Template Method is for when the order of the steps is fixed and only one step changes. This article builds both in a small Spring Boot app, SlaDesk, starting from the code most of us write first. Where these patterns sit among the others is in the pattern atlas.
The if-ladder
How many hours until the first response? It depends on the plan, and on whether the ticket is urgent.
public record Ticket(String id, String plan, boolean urgent) {
}
// The ladder: a new plan means opening this method and adding a branch.
static int firstResponseHours(Ticket ticket) {
if (ticket.plan().equals("basic")) {
return ticket.urgent() ? 12 : 24;
} else if (ticket.plan().equals("pro")) {
return ticket.urgent() ? 4 : 8;
} else if (ticket.plan().equals("enterprise")) {
return 1;
} else {
throw new IllegalArgumentException("Unknown plan: " + ticket.plan());
}
}
T-101 basic -> 24h
T-102 pro -> 4h
T-103 enterprise -> 1h
For three plans this is fine. The plan is a string compared by hand, so a typo like "Pro" falls into the else and throws at run time. The real cost shows up when a fourth plan arrives and this method has to be opened and edited again.
Strategy as Spring beans
The caller asks one question, and the plan chooses the answer:
public interface SlaPolicy {
// One question, answered differently by each plan.
int firstResponseHours(Ticket ticket);
}
@Component("pro")
public class ProSla implements SlaPolicy {
@Override
public int firstResponseHours(Ticket ticket) {
return ticket.urgent() ? 4 : 8;
}
}
The bean name is the plan. BasicSla and EnterpriseSla follow the same shape. The service never names them:
@Service
public class SlaService {
// Spring fills the map: bean name (the plan) -> the policy bean with that name.
private final Map<String, SlaPolicy> policies;
public SlaService(Map<String, SlaPolicy> policies) {
this.policies = policies;
}
public int firstResponseHours(Ticket ticket) {
SlaPolicy policy = policies.get(ticket.plan());
if (policy == null) {
throw new IllegalArgumentException("Unknown plan: " + ticket.plan());
}
return policy.firstResponseHours(ticket);
}
public TreeSet<String> plans() {
return new TreeSet<>(policies.keySet());
}
}
Asking for a Map<String, SlaPolicy> in the constructor makes Spring inject every SlaPolicy bean, keyed by bean name. The ladder becomes a lookup and one call. A runner sends four tickets, the last one on a plan that does not exist yet:
plans: [basic, enterprise, pro]
T-101 basic -> 24h
T-102 pro -> 4h
T-103 enterprise -> 1h
T-104 premium -> Unknown plan: premium
Now add the premium plan:
@Component("premium")
public class PremiumSla implements SlaPolicy {
// The whole change for a new plan: this file. Nothing else is edited.
@Override
public int firstResponseHours(Ticket ticket) {
return ticket.urgent() ? 1 : 2;
}
}
plans: [basic, enterprise, premium, pro]
T-101 basic -> 24h
T-102 pro -> 4h
T-103 enterprise -> 1h
T-104 premium -> 1h
SlaService, the runner and the other policies were not touched. The map has four entries.
Two smaller shapes for the same idea
A class per plan is not always worth it. Two lighter styles do the same job:
// Style 1: one lambda per plan. Fine while each rule is a single line.
static final Map<String, ToIntFunction<Ticket>> RULES = Map.of(
"basic", ticket -> ticket.urgent() ? 12 : 24,
"pro", ticket -> ticket.urgent() ? 4 : 8,
"enterprise", ticket -> 1);
// Style 2: the plans are a closed set, so the compiler checks that every one is handled.
sealed interface Plan permits Basic, Pro, Enterprise {
}
record Basic() implements Plan {
}
record Pro() implements Plan {
}
record Enterprise() implements Plan {
}
static int hours(Plan plan, boolean urgent) {
return switch (plan) {
case Basic basic -> urgent ? 12 : 24;
case Pro pro -> urgent ? 4 : 8;
case Enterprise enterprise -> 1;
};
}
lambda: 4h
sealed: 4h
The switch has no default. Add a Premium record to permits without a case and the file stops compiling, because the switch expression no longer covers every input. (Sealed types are covered in Java sealed classes.)
| Shape | Use it when | A fourth plan means |
|---|---|---|
| Strategy beans | Each policy has its own logic, dependencies or tests | One new class, nothing else edited |
| Lambda map | Each rule fits on one line | One new entry in the map |
| Sealed interface and switch | The set of plans is closed and known | The compiler flags every switch without the new case |
Start with the smallest shape that fits, and move to beans when a rule needs its own class. The Python version of the registry idea is in strategy and factory with a dict registry.
Template Method: the skeleton stays put
Importing tickets from a file is always parse, validate, save, report. Only parsing differs by format. Template Method keeps the order in a base class and leaves the changing step to subclasses:
public abstract class ImportJob {
// The skeleton: parse, validate, save, report. final, so no subclass can change the order.
public final void run(List<String> lines) {
int saved = 0, rejected = 0;
for (String line : lines) {
Ticket ticket = parse(line);
if (!isValid(ticket)) {
rejected++;
continue;
}
save(ticket);
saved++;
}
report(saved, rejected);
}
// The one step every format does differently.
protected abstract Ticket parse(String line);
// Steps with a sensible default that a subclass may replace.
protected boolean isValid(Ticket ticket) {
return !ticket.id().isBlank() && !ticket.plan().isBlank();
}
protected void save(Ticket ticket) {
System.out.println("saved " + ticket.id());
}
protected void report(int saved, int rejected) {
System.out.println(saved + " saved, " + rejected + " rejected");
}
}
public class CsvImport extends ImportJob {
@Override
protected Ticket parse(String line) {
String[] part = line.split(",", -1);
return new Ticket(part[0].trim(), part[1].trim(), Boolean.parseBoolean(part[2].trim()));
}
}
PipeImport splits on | and reads Y as urgent. Nothing else differs.
new CsvImport().run(List.of("T-201, pro, true", "T-202, basic, false", ", basic, false"));
new PipeImport().run(List.of("T-301 | enterprise | N", "T-302 | pro | Y"));
-- csv
saved T-201
saved T-202
2 saved, 1 rejected
-- pipe
saved T-301
saved T-302
2 saved, 0 rejected
The CSV row with no id is rejected by the shared rule. A third format would be a third small class, and the skeleton is not copied again. Remove final from run() and a subclass could override it, skip validation and save the bad row.
Recap
| Pattern | What is fixed | What varies | In SlaDesk |
|---|---|---|---|
| Strategy | The question the caller asks | The answer, one class per policy | SlaPolicy beans in a Map |
| Template Method | The order of the steps | One step, in a subclass | ImportJob.run(), parse() |
The next pattern, State, handles rules that depend on where an object is in its life: the State pattern for a ticket lifecycle.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Classes and Objects: One Blueprint, Many Cars
Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.
Java Constructors and the this Keyword
A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.
Java Instance Methods, Getters, Setters and toString
Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.
Java static: Fields, Methods and Blocks Shared by the Whole Class
A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.
