Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • 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
  • The State Pattern in Modern Java: A Ticket Lifecycle as Sealed Records, Where an Illegal Move Does Not Compile
  • When Not to Use a Design Pattern: Five Java Smells, the Patterns the Language Replaced, and a One-Page ADR for Saying No
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Object-Oriented Programming

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.

SlaService holds a map from plan name to policy bean: basic to BasicSla, pro to ProSla, enterprise to EnterpriseSla, and the new premium entry to PremiumSla. A ticket's plan picks one entry, and that policy answers. Adding premium adds one bean and one entry; SlaService is unchanged. SlaServicepolicies.get(plan) Map<String, SlaPolicy> "basic""pro""enterprise" "premium" (new) BasicSlaProSlaEnterpriseSlaPremiumSla
A new plan is a new bean and a new map entry. Nothing else changes.

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.)

ShapeUse it whenA fourth plan means
Strategy beansEach policy has its own logic, dependencies or testsOne new class, nothing else edited
Lambda mapEach rule fits on one lineOne new entry in the map
Sealed interface and switchThe set of plans is closed and knownThe 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

PatternWhat is fixedWhat variesIn SlaDesk
StrategyThe question the caller asksThe answer, one class per policySlaPolicy beans in a Map
Template MethodThe order of the stepsOne step, in a subclassImportJob.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.

Keep going in Java · 45 of 82

Previous
Java Record Patterns: Unpacking a Record
Next post
The State Pattern in Modern Java: A Ticket Lifecycle as Sealed Records, Where an Illegal Move Does Not Compile
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • The if-ladder
  • Strategy as Spring beans
  • Two smaller shapes for the same idea
  • Template Method: the skeleton stays put
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.