Skip to content

Template Method: A Fixed Algorithm With Steps Subclasses Fill In

Learn the Template Method pattern by building a bike-share ride-closing flow where the base class fixes the steps and subclasses supply the details.

13 min readDesign patternBehavioural

Define the skeleton of an algorithm in a base-class operation and defer some steps to subclasses. Subclasses can redefine those steps, but they cannot change the algorithm's overall structure or the order in which the steps run.

Template Method puts the outline of an algorithm in one base-class method and leaves particular steps for subclasses to fill in. The order of the steps never changes. Only the steps themselves vary. In this guide you will build the end-of-ride logic for a bike-share operator with three vehicle types. You will see why copying the flow three times went wrong, how a single template method fixed it, and what interviewers usually ask: hooks versus abstract steps, the Hollywood principle, and when Strategy is the better choice.

The problem

A situation where the obvious design starts to hurt.

Fernway is a bike-share operator with 2,400 vehicles in one city: classic bikes, e-bikes and e-scooters. When a rider ends a trip, the backend has to close the ride. It checks that the vehicle was parked correctly, rounds the trip up to whole minutes, computes the fare, applies the $15.00 per-ride cap, flags electric vehicles whose battery is under 20%, and produces a receipt line.

The four-person rides team first wrote this as three separate classes: ClassicBikeService, EBikeService and ScooterService. Each one held about 40 lines that were nearly identical. Only three things actually differed between vehicles. Classic bikes and e-bikes must be returned to a dock, while scooters need a parking photo. Each vehicle has its own unlock fee and per-minute rate. Classic bikes have no battery to check.

The copies drifted apart. When the fare cap was introduced, someone added it to the classic and e-bike services and forgot the scooter one, so a 50-minute scooter ride was billed $20.00 instead of $15.00. A later change to round partial minutes up landed in two files out of three. Every rule that applies to all vehicles now has to be edited in three places, and reviewers have to diff three long methods to find the parts that are actually different.

The team wants the shared flow written once, so that a new rule like the cap goes into one place and every vehicle picks it up. Each vehicle type should only describe what makes it different.

The solution

What the pattern proposes.

Move the flow into an abstract base class, RideCloser, with one method, closeRide(ride), that runs every step in a fixed order. This is the template method. Mark it final where the language allows, so subclasses cannot reorder or skip steps.

The steps that differ become methods that closeRide calls:

checkParking(ride), unlockFeeCents() and perMinuteCents() are abstract. Every vehicle must provide them because there is no sensible default.

tracksBattery() is a hook. The base class supplies a default (false), and only the e-bike and scooter subclasses override it to return true. Hooks give subclasses an optional place to plug in without forcing every subclass to implement it.

The invariant steps stay private to the base class: rounding seconds up to minutes, applying the $15.00 cap, comparing the battery level against 20% and formatting the receipt. Each subclass now holds a few lines of configuration instead of a full copy of the flow. The cap that was missed for scooters now lives in exactly one place and covers every vehicle, including any type added later.

Control is inverted. Subclasses never call the base class to run the ride; the base class calls them at the moments it chooses. This is often called the Hollywood principle: don't call us, we'll call you.

An everyday analogy

The same idea, outside software.

Think of a driving test. Every examiner follows the same order: check the learner's documents, do the eyesight check, drive the route, then give the result. A motorcycle examiner and a truck examiner run that same sequence, but the route they drive and the manoeuvres they ask for differ, and only the truck test includes an inspection of the trailer coupling. The test centre fixes the order and the pass rules, and each vehicle category fills in its own pieces. An examiner cannot decide to give the result before the drive.

Structure

The pieces and how they relate.

RideCloser.closeRide() fixes the step order; each vehicle subclass supplies parking rules, prices and optionally the battery hook.TripService calls RideCloser (closeRide(ride)). ClassicBikeCloser inherits from RideCloser. EBikeCloser inherits from RideCloser. ScooterCloser inherits from RideCloser.TripServicecallscloseRide(ride)«abstract»RideCloserfinal closeRide();abstract steps; hoo…Fixed orderparking, minutes,fare, cap, battery…ClassicBikeCloserdock required; 100 +15/minEBikeCloserdock required; 100 +30/min; batteryScooterCloserphoto required; 50 +39/min; batterycloseRide(ride)
RideCloser.closeRide() fixes the step order; each vehicle subclass supplies parking rules, prices and optionally the battery hook.

Participants

Abstract class (RideCloser)
Owns the template method closeRide, which runs every step in a fixed order. Implements the invariant steps itself: minute rounding, the $15.00 cap, the battery threshold and receipt formatting.
Primitive operations (checkParking, unlockFeeCents, perMinuteCents)
Abstract steps that every subclass must implement. They hold the parts of the algorithm that genuinely differ per vehicle.
Hook (tracksBattery)
An optional step with a default in the base class. Subclasses override it only when they need to; classic bikes keep the default false.
Concrete classes (ClassicBikeCloser, EBikeCloser, ScooterCloser)
Fill in the abstract steps and, where relevant, override the hook. They never call closeRide from inside or change the order of steps.
Client (TripService)
Picks the right closer for the vehicle and calls closeRide. It depends only on the abstract RideCloser type.

Pseudocode

The solution to the scenario, language-neutral.

abstract class RideCloser
    const DAILY_CAP_CENTS = 1500
    const LOW_BATTERY_PERCENT = 20

    final method closeRide(ride)
        problem = checkParking(ride)
        if problem is not null
            fail(vehicleName() + " " + ride.id + ": " + problem)
        minutes = ceil(ride.seconds / 60)
        cents = min(unlockFeeCents() + perMinuteCents() * minutes, DAILY_CAP_CENTS)
        flagged = tracksBattery() and ride.battery < LOW_BATTERY_PERCENT
        return receipt(ride.id, vehicleName(), minutes, cents, flagged)

    abstract method vehicleName()
    abstract method checkParking(ride)
    abstract method unlockFeeCents()
    abstract method perMinuteCents()
    method tracksBattery()            // hook
        return false

class ClassicBikeCloser extends RideCloser
    checkParking(ride): return null if ride.docked else "must be returned to a dock"
    unlockFeeCents(): return 100
    perMinuteCents(): return 15

class EBikeCloser extends RideCloser
    checkParking(ride): return null if ride.docked else "must be returned to a dock"
    unlockFeeCents(): return 100
    perMinuteCents(): return 30
    tracksBattery(): return true

class ScooterCloser extends RideCloser
    checkParking(ride): return null if ride.hasParkingPhoto else "needs a parking photo"
    unlockFeeCents(): return 50
    perMinuteCents(): return 39
    tracksBattery(): return true

// client
print new ScooterCloser().closeRide(ride r3, 3000 s)   // 50 min, raw $20.00, capped to $15.00

The code

The same solution in TypeScript, Python and PHP.

interface Ride {
  id: string;
  seconds: number;
  docked: boolean;
  hasParkingPhoto: boolean;
  batteryPercent: number | null;
}

abstract class RideCloser {
  static readonly DAILY_CAP_CENTS = 1500;
  static readonly LOW_BATTERY_PERCENT = 20;

  // Template method: the order of steps is fixed here. Do not override.
  closeRide(ride: Ride): string {
    const problem = this.checkParking(ride);
    if (problem !== null) {
      throw new Error(`${this.vehicleName()} ${ride.id}: ${problem}`);
    }
    const minutes = Math.ceil(ride.seconds / 60);
    const raw = this.unlockFeeCents() + this.perMinuteCents() * minutes;
    const cents = Math.min(raw, RideCloser.DAILY_CAP_CENTS);
    const flagged =
      this.tracksBattery() &&
      ride.batteryPercent !== null &&
      ride.batteryPercent < RideCloser.LOW_BATTERY_PERCENT;
    let line = `ride ${ride.id} (${this.vehicleName()}): ${minutes} min, $${(cents / 100).toFixed(2)}`;
    if (flagged) {
      line += ", flagged for charging";
    }
    return line;
  }

  protected abstract vehicleName(): string;
  protected abstract checkParking(ride: Ride): string | null;
  protected abstract unlockFeeCents(): number;
  protected abstract perMinuteCents(): number;

  // Hook: optional, with a default.
  protected tracksBattery(): boolean {
    return false;
  }
}

class ClassicBikeCloser extends RideCloser {
  protected vehicleName(): string { return "classic bike"; }
  protected checkParking(ride: Ride): string | null {
    return ride.docked ? null : "must be returned to a dock";
  }
  protected unlockFeeCents(): number { return 100; }
  protected perMinuteCents(): number { return 15; }
}

class EBikeCloser extends RideCloser {
  protected vehicleName(): string { return "e-bike"; }
  protected checkParking(ride: Ride): string | null {
    return ride.docked ? null : "must be returned to a dock";
  }
  protected unlockFeeCents(): number { return 100; }
  protected perMinuteCents(): number { return 30; }
  protected tracksBattery(): boolean { return true; }
}

class ScooterCloser extends RideCloser {
  protected vehicleName(): string { return "scooter"; }
  protected checkParking(ride: Ride): string | null {
    return ride.hasParkingPhoto ? null : "needs a parking photo";
  }
  protected unlockFeeCents(): number { return 50; }
  protected perMinuteCents(): number { return 39; }
  protected tracksBattery(): boolean { return true; }
}

const jobs: Array<[RideCloser, Ride]> = [
  [new ClassicBikeCloser(), { id: "r1", seconds: 690, docked: true, hasParkingPhoto: false, batteryPercent: null }],
  [new EBikeCloser(), { id: "r2", seconds: 1500, docked: true, hasParkingPhoto: false, batteryPercent: 14 }],
  [new ScooterCloser(), { id: "r3", seconds: 3000, docked: false, hasParkingPhoto: true, batteryPercent: 60 }],
  [new ScooterCloser(), { id: "r4", seconds: 400, docked: false, hasParkingPhoto: false, batteryPercent: 70 }],
];

for (const [closer, ride] of jobs) {
  try {
    console.log(closer.closeRide(ride));
  } catch (e) {
    console.log(`rejected: ${(e as Error).message}`);
  }
}
// ride r1 (classic bike): 12 min, $2.80
// ride r2 (e-bike): 25 min, $8.50, flagged for charging
// ride r3 (scooter): 50 min, $15.00
// rejected: scooter r4: needs a parking photo

When to use it

Situations where it pays off.

  • Several classes run the same sequence of steps and differ only in a few of them.

    Writing the sequence once removes the duplicated flow and keeps shared rules, like Fernway's fare cap, in a single place where they cannot drift apart.

  • You need to guarantee that a process always runs in a specific order, such as validating before charging.

    The template method owns the order and can be made final, so subclasses can change a step's behaviour but cannot skip or reorder it.

  • You are writing a framework or base class and want extension points without exposing the whole algorithm.

    Abstract steps and hooks define exactly where users may plug in. Everything else stays under the framework's control.

  • The variations are known at compile time and each variant is naturally its own type.

    Inheritance is a simple fit when a vehicle type never changes its pricing behaviour at runtime. If you need to swap behaviour per call, Strategy fits better.

How to implement it

Steps to introduce it in existing code.

  1. Write out the algorithm as it exists in each duplicated class and line the versions up side by side. Mark which lines are identical and which differ.

  2. Create an abstract base class and add the template method containing the full sequence. Make it final if your language supports it.

  3. Turn each differing part into a separate method call inside the template method. Use extract function on the existing code to get clean step boundaries.

  4. Decide for each step whether it is abstract (every subclass must supply it) or a hook (a sensible default exists). Keep hooks few; each one is a place the algorithm can be bent.

  5. Move the invariant steps, such as rounding and the cap, into the base class and keep them private or protected.

  6. Turn each old class into a subclass that implements only its steps. Delete the duplicated flow, run the tests for every variant and confirm outputs match.

Pros and cons

What you gain and what you pay.

Pros

  • The shared algorithm lives in one place, so a cross-cutting rule is added once and applies to every variant.
  • Subclasses stay small and only express what makes them different, which makes reviews and new variants quick.
  • The base class controls step order, so variants cannot accidentally skip validation or apply the cap before computing the fare.
  • Hooks let you offer optional extension points without forcing every subclass to implement them.

Cons

  • It relies on inheritance, so each variant is locked into one base class and cannot mix steps from two hierarchies.
  • Following the flow means jumping between the base class and the subclass, which gets harder as the number of steps and hooks grows.
  • A subclass can still break the contract inside a step, for example by having a hook throw or produce a side effect the skeleton does not expect.
  • Changing the skeleton affects every subclass at once, which is the point but also a risk when the subclasses live in other teams' code.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

What is the difference between an abstract step and a hook?

An abstract step has no implementation in the base class, so every subclass must provide one; Fernway's perMinuteCents is an example. A hook has a default implementation, often a no-op or false, and subclasses override it only if they need to, like tracksBattery. Use abstract steps for things that always differ and hooks for optional variations.

How does Template Method differ from Strategy?

Both let you vary part of an algorithm. Template Method uses inheritance: the subclass is the variation, chosen when you pick the class. Strategy uses composition: the context holds a strategy object you can replace at runtime and combine with others. In an interview, say that Template Method suits a fixed skeleton with a few varying steps, and Strategy suits interchangeable whole algorithms or behaviour that changes per call.

What is the Hollywood principle and how does it apply here?

It means 'don't call us, we'll call you'. Subclasses do not drive the process; the base class's template method calls their steps when it decides to. This inversion of control is what lets the base class guarantee the order of steps, for example that parking is always checked before the fare is computed.

How do I stop a subclass from overriding the template method?

Use the language feature where it exists: final in PHP and Java, sealed overrides in C#. Python's typing.final is enforced by type checkers such as mypy, not at runtime. TypeScript has no final methods, so you rely on a comment, code review or a lint rule.

How should I test a template method?

Test the skeleton once with a small test-only subclass that returns fixed values from each step, and assert the invariant rules: rounding, the cap, the battery threshold. Then test each real subclass through closeRide with a few rides that exercise its own steps. That avoids re-testing the shared flow for every vehicle type.

When does Template Method become a bad fit?

When the number of hooks keeps growing, when subclasses override steps just to disable them, or when you need to mix steps from different variants, such as scooter parking with e-bike pricing. At that point, extract the varying steps into separate objects and compose them, which moves you toward Strategy.

Next guide10 of 10 · Behavioral patternsVisitor Pattern: Add Operations Without Editing Your ClassesRead the next one