Strategy or Template Method?
Strategy and Template Method both let one step of a routine vary: Strategy hands the step in as an object or function (has-a), Template Method leaves it for a subclass to fill in (is-a); a look-alike table, a run-time change and a second varying step show what each costs, and why most teams reach for Strategy first.
Journeyman · OOP · Updated
After this lesson you can
- Tell Strategy from Template Method by how each lets a step vary: an object handed in, or a subclass
- Choose Strategy or Template Method for a problem, and say what each choice costs
Key takeaways
- Both patterns keep a routine in one place and let a step vary. Strategy fills the gap with something handed in; Template Method fills it with a subclass.
- Strategy is has-a (composition): the step can change while the program runs, and several varying steps combine freely.
- Template Method is is-a (inheritance): the order of the steps is protected, but each combination of variations is a new subclass, fixed when the object is made.
- Most teams reach for Strategy first, as Module 1's advice to prefer composition says; Template Method still fits a fixed routine with one or two known gaps, as in framework base classes.
Before this: Strategy: When the Rule Needs a Class of Its Own, Template Method: Same Routine, Your Own Step, and Prefer Composition to Inheritance (Module 1).
The last lesson ended with the same labels written two ways: as a base class with a barcode gap that each carrier's subclass fills in, and as one Label class handed its barcode step as a function. Both print the same lines today. They part ways the moment the next request arrives, and SameDay's is already here: rush packages, with their own barcode, SD-RUSH/43, picked at the counter for each package. This lesson puts the two side by side, so you can tell them apart and choose between them.
The same gap, filled two ways
Both patterns start from the same place: a routine written once, with one step that varies. The difference is who fills the gap:

- Template Method: is-a. A SameDay label is a label. The gap is an abstract method, and the subclass fills it in when it's written. Which barcode a label makes is decided by which class it is.
- Strategy: has-a. A label has a barcode step. The gap is a field or a parameter, and whoever makes or uses the label hands the step in. Which barcode a label makes is decided by what it was handed.
Rush labels: a choice made while the program runs
With Template Method, rush is another subclass, SameDayRushLabel, and the counter has to make a different kind of label object for rush packages. When EcoFreight asks for rush labels too, that's EcoFreightRushLabel; three carriers with two barcode styles each is six subclasses, and a third style is nine.
With Strategy, rush is one more barcode step, and the counter hands in whichever one this package needs:
// SameDay's counter picks the barcode step for each package: regular or rush.
Dictionary<string, Func<Package, string>> barcodes = new Dictionary<string, Func<Package, string>>
{
["regular"] = parcel => quot;SD/{parcel.Id}",
["rush"] = parcel => quot;SD-RUSH/{parcel.Id}"
};
Label sameDay = new Label("SameDay");
Console.WriteLine(sameDay.Make(new Package(42, "Maya", "Oak Ave"), 1500, barcodes["regular"]));
Console.WriteLine(sameDay.Make(new Package(43, "Sam", "Pine Rd"), 1500, barcodes["rush"]));
record Package(int Id, string Recipient, string Street);
class Label
{
private readonly string carrier;
public Label(string carrier) { this.carrier = carrier; }
// The routine, written once; the barcode step is handed in for each package.
public string Make(Package parcel, int cents, Func<Package, string> barcode)
{
string address = quot;To: {parcel.Recipient}, {parcel.Street}";
string rate = quot;${cents / 100}.{cents % 100:D2}";
return quot;{carrier} | {address} | {barcode(parcel)} | {rate}";
}
}
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
SameDay | To: Sam, Pine Rd | SD-RUSH/43 | $15.00
record Package(int id, String recipient, String street) {}
class Label {
String carrier;
Label(String carrier) { this.carrier = carrier; }
// The routine, written once; the barcode step is handed in for each package.
String make(Package parcel, int cents, Function<Package, String> barcode) {
String address = "To: " + parcel.recipient() + ", " + parcel.street();
String rate = " quot; + cents / 100 + "." + String.format("%02d", cents % 100);
return carrier + " | " + address + " | " + barcode.apply(parcel) + " | " + rate;
}
}
void main() {
// SameDay's counter picks the barcode step for each package: regular or rush.
Map<String, Function<Package, String>> barcodes = Map.of(
"regular", p -> "SD/" + p.id(),
"rush", p -> "SD-RUSH/" + p.id());
Label sameDay = new Label("SameDay");
IO.println(sameDay.make(new Package(42, "Maya", "Oak Ave"), 1500, barcodes.get("regular")));
IO.println(sameDay.make(new Package(43, "Sam", "Pine Rd"), 1500, barcodes.get("rush")));
}
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
SameDay | To: Sam, Pine Rd | SD-RUSH/43 | $15.00
class Package:
def __init__(self, id, recipient, street):
self.id = id
self.recipient = recipient
self.street = street
class Label:
def __init__(self, carrier):
self.carrier = carrier
def make(self, parcel, cents, barcode):
"""The routine, written once; the barcode step is handed in for each package."""
address = f"To: {parcel.recipient}, {parcel.street}"
rate = f"${cents // 100}.{cents % 100:02d}"
return f"{self.carrier} | {address} | {barcode(parcel)} | {rate}"
# SameDay's counter picks the barcode step for each package: regular or rush.
barcodes = {"regular": lambda p: f"SD/{p.id}", "rush": lambda p: f"SD-RUSH/{p.id}"}
same_day = Label("SameDay")
print(same_day.make(Package(42, "Maya", "Oak Ave"), 1500, barcodes["regular"]))
print(same_day.make(Package(43, "Sam", "Pine Rd"), 1500, barcodes["rush"]))
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
SameDay | To: Sam, Pine Rd | SD-RUSH/43 | $15.00
class Package {
constructor(id, recipient, street) {
this.id = id;
this.recipient = recipient;
this.street = street;
}
}
class Label {
constructor(carrier) {
this.carrier = carrier;
}
// The routine, written once; the barcode step is handed in for each package.
make(parcel, cents, barcode) {
const address = `To: ${parcel.recipient}, ${parcel.street}`;
const rate = `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
return `${this.carrier} | ${address} | ${barcode(parcel)} | ${rate}`;
}
}
// SameDay's counter picks the barcode step for each package: regular or rush.
const barcodes = new Map([
["regular", (p) => `SD/${p.id}`],
["rush", (p) => `SD-RUSH/${p.id}`],
]);
const sameDay = new Label("SameDay");
console.log(sameDay.make(new Package(42, "Maya", "Oak Ave"), 1500, barcodes.get("regular")));
console.log(sameDay.make(new Package(43, "Sam", "Pine Rd"), 1500, barcodes.get("rush")));
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
SameDay | To: Sam, Pine Rd | SD-RUSH/43 | $15.00
class Package {
id: number;
recipient: string;
street: string;
constructor(id: number, recipient: string, street: string) {
this.id = id;
this.recipient = recipient;
this.street = street;
}
}
type Barcode = (parcel: Package) => string;
class Label {
carrier: string;
constructor(carrier: string) {
this.carrier = carrier;
}
// The routine, written once; the barcode step is handed in for each package.
make(parcel: Package, cents: number, barcode: Barcode): string {
const address = `To: ${parcel.recipient}, ${parcel.street}`;
const rate = `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
return `${this.carrier} | ${address} | ${barcode(parcel)} | ${rate}`;
}
}
// SameDay's counter picks the barcode step for each package: regular or rush.
const barcodes = new Map<string, Barcode>([
["regular", (p) => `SD/${p.id}`],
["rush", (p) => `SD-RUSH/${p.id}`],
]);
const sameDay = new Label("SameDay");
console.log(sameDay.make(new Package(42, "Maya", "Oak Ave"), 1500, barcodes.get("regular")!));
console.log(sameDay.make(new Package(43, "Sam", "Pine Rd"), 1500, barcodes.get("rush")!));
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
SameDay | To: Sam, Pine Rd | SD-RUSH/43 | $15.00
One label object made both labels. The counter chose the step for each package, at the moment it was needed, and a third barcode style would be one more entry in barcodes, not three more subclasses.
The look-alike table
| Pattern | What it's for | Strengths | Weaknesses | Pick it when |
|---|---|---|---|---|
| Template Method | A routine whose steps always run in the same order, with one or two steps each subclass fills in | The order of the steps can't be broken by a subclass; the shared steps live in one place; the compiler shows exactly which steps a new subclass must fill in | Every combination of variations is a new subclass; the choice is fixed when the object is made; each subclass is tied to its base class, so a change to the routine reaches all of them | The routine is fixed, only one or two steps vary, and the kinds are few and known, as in a framework's base class or a test runner's set-up and clean-up |
| Strategy | A rule or step that varies, handed in from outside | Swap it while the program runs; several varying steps combine freely; each step can be tested on its own; no inheritance; in most languages it can be a single function | One more thing to make and hand in; the reader has to find out what was handed in; nothing stops the caller from handing in a step that doesn't fit | The varying part changes at run time, more than one part varies, or the parts are written by someone else (a partner, another team, the user's settings) |
Why most teams reach for Strategy first
Module 1's Prefer Composition to Inheritance is this choice in miniature. A subclass is decided once, when the code is written; a strategy can be decided by data, at the counter, per package. Two things that vary (barcode style and, next month, label size) stay two small pieces instead of becoming a grid of subclasses. And since every language in this course can pass a function as a value, a strategy is often one line.
Template Method still earns its place when the order is the point: a framework that must run set-up, then your step, then clean-up, every time, and doesn't want anyone to be able to skip a step. That's why it's everywhere inside frameworks, and rarer in the code you write on top of them.
Telling them apart in code
Ask two questions of the code in front of you:
- Where does the varying step come from? If it's a method a subclass overrides, it's Template Method. If it's a field, a constructor argument or a parameter, it's Strategy.
- Can it change while the program runs, on the same object? Strategy's can; Template Method's can't.
Check yourself
2 questions to try on the lesson page.
So what
Both patterns give a routine one home and let one step vary; they differ in who fills the gap. Reach for the handed-in step first, because it bends to run-time choices and combinations; keep the subclass for a fixed routine whose order matters more than its flexibility.