TL;DR
Strategy and Template Method, side by side in Java, Node.js, and Python: real code, the framework built-ins, and when each pattern earns its keep.
Strategy and Template Method are the two patterns every working codebase reaches for when one piece of behaviour needs to vary — and they are constantly confused with each other, because both solve "the same code, with one part different". The difference is what varies. Strategy swaps the whole algorithm at runtime: the caller picks an implementation and the context runs it. Template Method fixes the skeleton — the order of the steps — and lets one step vary: the base class runs the algorithm and subclasses fill in the hook. Both come from the Gang of Four's Design Patterns (Gamma, Helm, Johnson, Vlissides, Addison-Wesley, 1994), and both are still in daily use because the problem they solve never went away: behaviour that changes independently of the code that invokes it.
This article builds the same two examples three times — a pricing rule and a report generator — in Java, in TypeScript on Node.js, and in Python. Same shape, different idioms. The short version up front: reach for Strategy when the algorithm is chosen at runtime, per request; reach for Template Method when the order of the steps is the invariant and only one step changes; and if neither varies, you need neither pattern — a plain function is the whole design.
Strategy: swap the whole algorithm at runtime
Strategy is the simpler of the two to recognise in the wild: a context holds a reference to an interface, and the concrete implementation is supplied from outside — by configuration, by dependency injection, or by the caller. The context never knows which implementation it is running. Adding a new algorithm means adding a new class or function; nothing that already works changes.
Strategy in Java: an interface, plus Spring's Map injection
The pricing example is the canonical one, because pricing genuinely is a runtime decision: the same checkout runs standard pricing, a flash sale, or a student discount depending on the request. The domain type is one small record:
import java.math.BigDecimal;
public record Order(long id, BigDecimal subtotal, boolean complete) {}The strategy is an interface with one method. Each pricing rule is a small final class that implements it — no shared state, no inheritance, nothing to get wrong:
public interface PricingStrategy {
BigDecimal price(Order order);
}
public final class StandardPricing implements PricingStrategy {
@Override
public BigDecimal price(Order order) {
return order.subtotal();
}
}
public final class FlashSalePricing implements PricingStrategy {
@Override
public BigDecimal price(Order order) {
return order.subtotal().multiply(new BigDecimal("0.60"));
}
}The context is the checkout service. The selection logic — which strategy runs for this request — is deliberately not in the context's head: it arrives as a constructor argument, and the caller or the container decides:
@Service
public class CheckoutService {
private final Map<String, PricingStrategy> strategies;
public CheckoutService(Map<String, PricingStrategy> strategies) {
// Spring injects every PricingStrategy bean, keyed by bean name.
this.strategies = strategies;
}
public BigDecimal checkout(Order order, String pricing) {
PricingStrategy strategy = strategies.get(pricing);
if (strategy == null) {
throw new IllegalArgumentException("Unknown pricing: " + pricing);
}
return strategy.price(order);
}
}Registration is a @Bean method per implementation — the same factory idiom from our creational patterns in Spring Boot guide, doing selection work here instead of creation work:
@Configuration
public class PricingConfig {
@Bean("standard")
public PricingStrategy standardPricing() {
return new StandardPricing();
}
@Bean("flash-sale")
public PricingStrategy flashSalePricing() {
return new FlashSalePricing();
}
}Two properties make this worth copying. First, CheckoutService has no if chain and no knowledge of any pricing rule — a new rule is a new @Bean method, and the service, its tests, and every other rule stay untouched. Second, testing is trivial: pass a fake PricingStrategy in the constructor and assert the service calls it. The pattern's cost is indirection — a reader has to look at the configuration to see which implementation runs — and that cost is only worth paying when there really are two or more algorithms. One implementation plus an interface is a switch statement wearing a costume.
Strategy in Node and TypeScript: functions are strategies
Java needs the interface because it has no first-class functions for this job; TypeScript does, and the pattern gets dramatically shorter. A strategy is a function type, each rule is a function, and the registry is a plain object:
interface Order {
id: number;
subtotal: number;
complete: boolean;
}
type PricingStrategy = (order: Order) => number;
const standard: PricingStrategy = (order) => order.subtotal;
const flashSale: PricingStrategy = (order) => order.subtotal * 0.6;
const strategies: Record<string, PricingStrategy> = {
standard,
'flash-sale': flashSale,
};
export function checkout(order: Order, pricing: string): number {
const strategy = strategies[pricing];
if (!strategy) {
throw new Error(`Unknown pricing: ${pricing}`);
}
return strategy(order);
}That is the entire pattern in TypeScript: no classes, no interfaces beyond the function type, no framework. The trade-off is the mirror image of Java's. Functions are the lightest possible strategy, and they are the right choice while the strategies are stateless — a pure function of the order. The moment a strategy needs state of its own — a rate table loaded once from a database, a client with a connection pool — a bare function starts accumulating closures and hidden dependencies, and that is the point to switch to a class implementing the same function type. The shape does not change; only the packaging does.
Strategy in Python: a dictionary of callables
Python lands in the same place as TypeScript, with even less ceremony. First-class functions and a dictionary are the registry:
from dataclasses import dataclass
@dataclass
class Order:
id: int
subtotal: float
complete: bool
def standard(order: Order) -> float:
return order.subtotal
def flash_sale(order: Order) -> float:
return order.subtotal * 0.6
STRATEGIES = {"standard": standard, "flash-sale": flash_sale}
def checkout(order: Order, pricing: str) -> float:
try:
return STRATEGIES[pricing](order)
except KeyError:
raise ValueError(f"Unknown pricing: {pricing}") from NoneThe same state rule applies as in TypeScript: when a strategy needs its own state, give it a class with a __call__ method and put instances in the same dictionary — the call site does not change, because it only ever calls a callable. Python's standard library is full of this shape wearing no pattern name at all: sorted(data, key=...) takes its comparison strategy as a function, and functools.singledispatch routes on the argument type. If your Python code already passes functions around, you are already using Strategy; naming it is what lets the team recognise the shape and extend it consistently instead of reinventing it per module.
The built-in version: NestJS Passport strategies
The clearest proof that Strategy is a framework-level idea, not a textbook exercise, is that NestJS ships it under its own name. Authentication is a textbook runtime-swappable algorithm: the same guard runs a JWT check, a Google OAuth check, or an API-key check depending on configuration. NestJS calls each one a strategy, and swapping the algorithm is a one-line provider change:
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET as string,
});
}
async validate(payload: { sub: string }) {
return { userId: payload.sub };
}
}The guard that consumes the strategy never knows which one is active — it calls validate and trusts the result. That is the pattern's whole contract, and it is also the test for whether your own use of Strategy is honest: if the caller has to know which implementation it holds, the interface is leaking. The NestJS authentication docs describe the same shape for OAuth, local username-and-password, and API-key strategies; adding a second login method is a new strategy class, not a change to the guard.
Template Method: fix the skeleton, vary one step
Template Method is the pattern for the opposite situation: the order of the steps is the invariant, and exactly one step is allowed to differ. The base class owns the algorithm's skeleton — it runs the steps in a fixed order — and the varying step is a method subclasses override. The classic failure mode is a base class whose subclasses each reimplement the whole flow slightly differently, drifting until no two of them agree on the order. Template Method deletes that drift by making the skeleton un-overridable and the variation point explicit.
Template Method in Java: the abstract class, done properly
The report generator is the textbook example because the skeleton is genuinely fixed: validate the input, format it, deliver it — in that order, every time. Only the format changes, per output type:
import java.util.List;
public abstract class ReportGenerator {
// The template method: final, so no subclass can reorder the steps.
public final String run(List<Order> orders) {
List<Order> valid = validate(orders);
String body = format(valid); // the hook — varies per subclass
return deliver(body);
}
protected List<Order> validate(List<Order> orders) {
return orders.stream().filter(Order::complete).toList();
}
protected abstract String format(List<Order> orders);
protected String deliver(String body) {
return body; // subclasses may override to email or store it
}
}
public final class CsvReport extends ReportGenerator {
@Override
protected String format(List<Order> orders) {
StringBuilder out = new StringBuilder("id,total\n");
for (Order order : orders) {
out.append(order.id()).append(',').append(order.subtotal()).append('\n');
}
return out.toString();
}
}Three details carry the whole pattern. First, run() is final — a subclass that overrides the skeleton has defeated the pattern, and the compiler should say so. Second, the hook is abstract, which forces every subclass to make a conscious decision about the varying step; a hook with a default body is for steps that are usually the same, and it should be used sparingly, because a default that silently applies is a bug waiting for a reader who never noticed it. Third, the fixed steps are protected, not private: subclasses can see them and reuse them, but callers cannot call them out of order. If a step needs to be callable by subclasses but never overridden, make it final too — the skeleton's integrity is the point.
Template Method in Node: an abstract class, plus stream.Transform
TypeScript has no final, so the discipline moves from the compiler to the team: the template method is documented as not-to-be-overridden, and code review enforces it. The shape is otherwise identical:
abstract class ReportGenerator {
// The skeleton is fixed; subclasses fill in format() only.
run(orders: Order[]): string {
const valid = orders.filter((o) => o.complete);
return this.format(valid);
}
protected abstract format(orders: Order[]): string;
}
class CsvReport extends ReportGenerator {
protected format(orders: Order[]): string {
const lines = ['id,total', ...orders.map((o) => `${o.id},${o.subtotal}`)];
return lines.join('\n');
}
}Node's standard library ships the pattern itself, and it is worth studying because it shows the shape at its best. stream.Transform owns the entire plumbing — buffering, backpressure, the readable and writable sides — and you implement exactly one hook:
import { Transform, type TransformCallback } from 'node:stream';
// Node's own Template Method: Transform owns the plumbing,
// and you implement one hook — _transform — and nothing else.
class UpperCase extends Transform {
_transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback): void {
callback(null, chunk.toString().toUpperCase());
}
}
process.stdin.pipe(new UpperCase()).pipe(process.stdout);Nobody who writes a Transform subclass reimplements backpressure. That is the pattern paying off: the hard, bug-prone part lives in the base class once, and every subclass gets it for free. If your own template method's base class is not carrying something genuinely hard — resource cleanup, error handling, ordering guarantees — the inheritance is not earning its keep, and a plain function with a callback parameter would be the simpler design.
Template Method in Python: abc, plus unittest.TestCase
Python's version uses abc to make the hook explicit, which matters in a language where nothing is enforced by the compiler:
from abc import ABC, abstractmethod
class ReportGenerator(ABC):
def run(self, orders):
valid = [o for o in orders if o.complete]
return self.format(valid) # the hook
@abstractmethod
def format(self, orders):
raise NotImplementedError
class CsvReport(ReportGenerator):
def format(self, orders):
lines = ["id,total"]
lines += [f"{o.id},{o.subtotal}" for o in orders]
return "\n".join(lines)Without ABC and @abstractmethod, a subclass that forgets format fails at runtime, deep inside a request, instead of at import time. The two decorators are the entire enforcement mechanism Python offers, and they are worth the two lines. Python's own standard library runs on the same shape: unittest.TestCase owns the order — setUp, the test method, tearDown — and your test class fills in the hooks, never the runner. Django's class-based views do the same thing one level up: View.dispatch() routes the request to your get() or post() method, so the framework owns the request lifecycle and you own the per-verb behaviour. When a framework you use every day is built on a pattern, that is the strongest evidence the pattern is load-bearing rather than academic.
The built-in version: Spring's JdbcTemplate
Spring's JdbcTemplate is the Template Method pattern as most Java developers actually meet it — and it shows the pattern's second form, where the varying step is supplied as a callback instead of a subclass. The template owns the fixed steps (open the connection, run the SQL, close everything, translate the exception); you supply the one step that differs, as a RowMapper:
// Spring's built-in Template Method: JdbcTemplate owns the fixed steps
// and you supply the variable step as a callback.
List<Order> orders = jdbcTemplate.query(
"SELECT id, total FROM orders WHERE complete = true",
(rs, rowNum) -> new Order(rs.getLong("id"), rs.getBigDecimal("total")));This is the same skeleton as ReportGenerator.run(), with the hook passed in rather than inherited. The Spring JDBC reference documents three callback types for the varying step — RowMapper for one row at a time, ResultSetExtractor when you need the whole result set, RowCallbackHandler for streaming rows somewhere without building a list — and the choice between them is the only decision the caller makes. The lesson generalises: Template Method by inheritance and Template Method by callback are the same pattern, and the callback form is usually the better one in a language with lambdas, because it composes — a caller can pass a different callback per call site — where inheritance fixes the variation per class. Spring chose the callback form for exactly that reason, and it is the form to copy when your skeleton's varying step is small.
Head-to-head: Strategy vs Template Method
| Strategy | Template Method | |
|---|---|---|
| What varies | The whole algorithm | One step of a fixed algorithm |
| When the choice is made | At runtime, per request or per configuration | At design time, per subclass |
| How you add a variant | New class or function, registered with the context | New subclass, or a new callback |
| The context knows | Only the interface | The full skeleton, and the hook's contract |
| Built-in examples | NestJS Passport strategies; Comparator; sorted(key=...) | Spring JdbcTemplate; Node Transform; unittest.TestCase |
| Failure mode | One implementation plus an interface — indirection with no decision | Deep inheritance, fragile base class — subclasses coupled to private steps |
| Cost | Indirection: the reader must find the active implementation | Coupling: the base class and its subclasses evolve together |
The table hides one practical rule worth stating plainly. Strategy composes: a context can hold two strategies at once, and a strategy can be passed to another strategy. Template Method does not compose — a subclass gets one base class, and two skeletons cannot be combined without a new class. That is why the default advice in modern code is to prefer Strategy, and to reach for Template Method only when the skeleton itself is the invariant worth protecting: the ordering, the cleanup, the error handling that must happen the same way every time. And the two patterns combine cleanly: a template method's hook step can itself be a strategy, so the skeleton stays fixed while the varying step is still chosen at runtime. That composition — a strategy inside a template step — is the answer when a design genuinely needs both.
Architecture decision: Strategy and Template Method in this codebase
if chains and copy-pasted flows by default. This decision applies to new code and to files already being touched.if/switch dispatch at the call site — no pattern at all. (c) Template Method by inheritance everywhere, including for runtime-swappable behaviour.Recommendation
For a new service in any of the three stacks, adopt three rules and enforce them in review. First, no algorithm selection in an if chain at the call site — if the behaviour varies by request, configuration, or tenant, it is a Strategy, registered once and injected. Second, no copy-pasted flow with one step changed — if the skeleton repeats, it is a Template Method, with the skeleton final (or documented as such in TypeScript and Python) and the varying step a single named hook. Third, prefer the callback form of Template Method when the varying step is small: a lambda passed to the template composes better than a subclass, and Spring's JdbcTemplate is the model to copy. For the companion patterns, our creational patterns in Spring Boot guide covers the factories that register strategies, and our Proxy, Decorator, and Adapter guide covers the structural patterns that wrap them.
For an existing service, the migration is incremental and safe. Replace one if chain at a time: extract each branch into a strategy, register it, and inject it — the call site gets shorter with every replacement, and the tests get easier, because each strategy is testable on its own. Replace one duplicated flow at a time: extract the skeleton into a template method, keep the existing behaviour as the first subclass, and delete the copies. Each replacement is a small, testable change, and the design gets visibly simpler with every one.
When NOT to use these patterns
run() final in Java; in TypeScript and Python, name it clearly, document it, and catch overrides in review.if that moved house.Strategy and Template Method survive because they name the two ways behaviour varies, and naming the variation is what lets a team extend it without breaking what already works. The patterns are small — an interface and a registry, a final method and a hook — and their value is entirely in the discipline around them: the selection logic lives in configuration, the skeleton lives in one place, and every new variant is an addition, never a modification. For the broader question of how these choices fit into a service's overall shape, our Hexagonal and Clean Architecture guide shows the same idea one level up — the domain owns the interface, the adapters implement it — and our modular monolith vs microservices guide is the decision to make before any of these patterns matter at all.
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.