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.
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
closeRidefrom inside or change the order of steps. - Client (TripService)
- Picks the right closer for the vehicle and calls
closeRide. It depends only on the abstractRideClosertype.
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.00The 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 photofrom abc import ABC, abstractmethod
from dataclasses import dataclass
from math import ceil
from typing import Optional, final
@dataclass
class Ride:
id: str
seconds: int
docked: bool
has_parking_photo: bool
battery_percent: Optional[int]
class RideCloser(ABC):
DAILY_CAP_CENTS = 1500
LOW_BATTERY_PERCENT = 20
@final
def close_ride(self, ride: Ride) -> str:
"""Template method: the order of steps is fixed here."""
problem = self.check_parking(ride)
if problem is not None:
raise ValueError(f"{self.vehicle_name()} {ride.id}: {problem}")
minutes = ceil(ride.seconds / 60)
raw = self.unlock_fee_cents() + self.per_minute_cents() * minutes
cents = min(raw, self.DAILY_CAP_CENTS)
flagged = (
self.tracks_battery()
and ride.battery_percent is not None
and ride.battery_percent < self.LOW_BATTERY_PERCENT
)
line = f"ride {ride.id} ({self.vehicle_name()}): {minutes} min, ${cents / 100:.2f}"
if flagged:
line += ", flagged for charging"
return line
@abstractmethod
def vehicle_name(self) -> str: ...
@abstractmethod
def check_parking(self, ride: Ride) -> Optional[str]: ...
@abstractmethod
def unlock_fee_cents(self) -> int: ...
@abstractmethod
def per_minute_cents(self) -> int: ...
def tracks_battery(self) -> bool:
"""Hook: optional, with a default."""
return False
class ClassicBikeCloser(RideCloser):
def vehicle_name(self) -> str:
return "classic bike"
def check_parking(self, ride: Ride) -> Optional[str]:
return None if ride.docked else "must be returned to a dock"
def unlock_fee_cents(self) -> int:
return 100
def per_minute_cents(self) -> int:
return 15
class EBikeCloser(RideCloser):
def vehicle_name(self) -> str:
return "e-bike"
def check_parking(self, ride: Ride) -> Optional[str]:
return None if ride.docked else "must be returned to a dock"
def unlock_fee_cents(self) -> int:
return 100
def per_minute_cents(self) -> int:
return 30
def tracks_battery(self) -> bool:
return True
class ScooterCloser(RideCloser):
def vehicle_name(self) -> str:
return "scooter"
def check_parking(self, ride: Ride) -> Optional[str]:
return None if ride.has_parking_photo else "needs a parking photo"
def unlock_fee_cents(self) -> int:
return 50
def per_minute_cents(self) -> int:
return 39
def tracks_battery(self) -> bool:
return True
if __name__ == "__main__":
jobs = [
(ClassicBikeCloser(), Ride("r1", 690, True, False, None)),
(EBikeCloser(), Ride("r2", 1500, True, False, 14)),
(ScooterCloser(), Ride("r3", 3000, False, True, 60)),
(ScooterCloser(), Ride("r4", 400, False, False, 70)),
]
for closer, ride in jobs:
try:
print(closer.close_ride(ride))
except ValueError as e:
print(f"rejected: {e}")
# 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<?php
declare(strict_types=1);
final class Ride
{
public function __construct(
public readonly string $id,
public readonly int $seconds,
public readonly bool $docked,
public readonly bool $hasParkingPhoto,
public readonly ?int $batteryPercent,
) {
}
}
abstract class RideCloser
{
public const DAILY_CAP_CENTS = 1500;
public const LOW_BATTERY_PERCENT = 20;
// Template method: the order of steps is fixed here.
final public function closeRide(Ride $ride): string
{
$problem = $this->checkParking($ride);
if ($problem !== null) {
throw new DomainException(sprintf('%s %s: %s', $this->vehicleName(), $ride->id, $problem));
}
$minutes = intdiv($ride->seconds + 59, 60);
$raw = $this->unlockFeeCents() + $this->perMinuteCents() * $minutes;
$cents = min($raw, self::DAILY_CAP_CENTS);
$flagged = $this->tracksBattery()
&& $ride->batteryPercent !== null
&& $ride->batteryPercent < self::LOW_BATTERY_PERCENT;
$line = sprintf('ride %s (%s): %d min, $%.2f', $ride->id, $this->vehicleName(), $minutes, $cents / 100);
if ($flagged) {
$line .= ', flagged for charging';
}
return $line;
}
abstract protected function vehicleName(): string;
abstract protected function checkParking(Ride $ride): ?string;
abstract protected function unlockFeeCents(): int;
abstract protected function perMinuteCents(): int;
// Hook: optional, with a default.
protected function tracksBattery(): bool
{
return false;
}
}
final class ClassicBikeCloser extends RideCloser
{
protected function vehicleName(): string { return 'classic bike'; }
protected function checkParking(Ride $ride): ?string
{
return $ride->docked ? null : 'must be returned to a dock';
}
protected function unlockFeeCents(): int { return 100; }
protected function perMinuteCents(): int { return 15; }
}
final class EBikeCloser extends RideCloser
{
protected function vehicleName(): string { return 'e-bike'; }
protected function checkParking(Ride $ride): ?string
{
return $ride->docked ? null : 'must be returned to a dock';
}
protected function unlockFeeCents(): int { return 100; }
protected function perMinuteCents(): int { return 30; }
protected function tracksBattery(): bool { return true; }
}
final class ScooterCloser extends RideCloser
{
protected function vehicleName(): string { return 'scooter'; }
protected function checkParking(Ride $ride): ?string
{
return $ride->hasParkingPhoto ? null : 'needs a parking photo';
}
protected function unlockFeeCents(): int { return 50; }
protected function perMinuteCents(): int { return 39; }
protected function tracksBattery(): bool { return true; }
}
$jobs = [
[new ClassicBikeCloser(), new Ride('r1', 690, true, false, null)],
[new EBikeCloser(), new Ride('r2', 1500, true, false, 14)],
[new ScooterCloser(), new Ride('r3', 3000, false, true, 60)],
[new ScooterCloser(), new Ride('r4', 400, false, false, 70)],
];
foreach ($jobs as [$closer, $ride]) {
try {
echo $closer->closeRide($ride), PHP_EOL;
} catch (DomainException $e) {
echo 'rejected: ', $e->getMessage(), PHP_EOL;
}
}
// 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 photoWhen 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.
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.
Create an abstract base class and add the template method containing the full sequence. Make it final if your language supports it.
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.
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.
Move the invariant steps, such as rounding and the cap, into the base class and keep them private or protected.
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.
- Strategy: swap the rule without touching who uses it
Strategy varies an algorithm by composition and can swap it at runtime; Template Method varies steps by inheritance and fixes them per class. Prefer Strategy when behaviour must change per call or combine freely.
- Factory Method: Let Subclasses Decide Which Object to Create
A factory method is often one of the steps inside a template method: the skeleton asks a subclass to create an object, then uses it in the remaining steps.
- Duplicate Code: When the Same Logic Lives in Several Places
Several classes repeating the same sequence with small differences is the classic signal that a template method can hold the shared flow.
- Extract function: give a fragment a name
Extracting each differing block into its own method is the first mechanical step toward turning a duplicated flow into abstract steps and hooks.
- Refused Bequest: Subclasses That Reject What They Inherit
If a subclass must override a step just to make it do nothing, the hierarchy may be wrong; that step should probably be a hook with a no-op default.
- Builder Pattern: Assemble Complex Objects Step by Step
A director in Builder runs a fixed sequence of steps too, but delegates them to a separate builder object rather than to subclasses of itself.
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.