Skip to content

Strategy vs State vs Template Method

Difficulty: Intermediate

Key concepts

  • strategy pattern
  • state pattern
  • template method pattern
  • composition vs inheritance
  • choosing a pattern
  • The question that separates Strategy, State, and Template Method: who chooses the variation, and when can it change?
  • How the same varying part, a pricing plan, looks as a Template Method and as a Strategy, and what each makes easy or hard.
  • Why an account’s stages are a State and not a Strategy, even though the two look the same in a class diagram.
  • How the difference shows in C++: inheritance against a held std::unique_ptr, and a public setter against a private one.

All three keep some code fixed and let one part vary. They differ in who picks the varying part, and when it can change:

  • Template Method: whoever creates the object picks it, by choosing which derived class to create. A base class fixes the steps; each derived class fills in the step that varies. The choice is made when the object is created, and it cannot change for that object’s life.
  • Strategy: someone outside picks it. The object holds the varying part behind an interface. A caller chooses it, at construction or later, if the context offers a setter (here, change_plan). The strategies do not know each other.
  • State: the object itself moves it. Each state handles events, and decides, as part of handling one, which state comes next. No caller chooses a state; callers only send events.

A small cloud-storage service bills each account once a month, on the gigabytes stored:

  • FR-1. There are three plans: flat (10.00 a month, whatever the usage), metered (0.05 per GB), and tiered (the first 50 GB free, then 0.08 per GB).
  • FR-2. Every bill follows the same steps, whatever the plan: the plan’s charge, capped at 50.00, then 20% tax, rounded to the cent.
  • FR-3. A customer may change plan at any time. The next bill uses the new plan.
  • FR-4. A new account gets two free months, and then becomes active by itself. If a payment fails, the account becomes overdue, and each bill adds a 5.00 late fee until a payment is received. There is nothing to pay during a trial, so recording a payment then is a mistake.
Requirement What varies Who changes it, and when
FR-1 the plan’s formula —
FR-2 nothing: the steps are fixed —
FR-3 which formula an account uses the customer, at any time
FR-4 the account’s stage the account, as months close and payments succeed or fail

The rows already point at the answer. The plan is chosen from outside, so it suits Strategy. The stage moves by itself, so it suits State. The fixed steps of FR-2 suit a Template Method’s skeleton, or simply one function. To see why, the plans are written twice below: once as a Template Method and once as a Strategy.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

template_form.hpp
// A month's bill, with the plan built into the class: a MeteredBill is
// always metered. The base class owns the steps every bill shares; a
// derived class fills in only the plan's charge and its name. Amounts are
// Cents, a whole number of cents (1'000 is 10.00; the ' only groups digits).
class MonthlyBill {
public:
// Virtual, so a bill deleted through a MonthlyBill pointer is
// destroyed properly. Copying is switched off (`= delete`), for every
// plan too: a bill is used where it is, never copied.
virtual ~MonthlyBill() = default;
MonthlyBill(const MonthlyBill&) = delete;
MonthlyBill& operator=(const MonthlyBill&) = delete;
// The fixed steps: the plan's charge, then the cap, then tax.
// Throws std::invalid_argument for negative usage.
// Not virtual, so no plan can change the order or skip the cap or tax.
Cents total(int gigabytes) const;
// Public, non-virtual, and it just asks the private virtual plan_name.
std::string_view plan() const { return plan_name(); }
protected:
// Only derived classes can create a MonthlyBill.
MonthlyBill() = default;
private:
// Pure virtual (`= 0`): each plan must supply them. Private: a plan can
// override them, but only MonthlyBill's own code can call them, so the
// charge is never seen without the cap and tax.
virtual Cents plan_charge(int gigabytes) const = 0; // the one step that varies
virtual std::string_view plan_name() const = 0;
};
// The three plans. `final`: no class derives from them. `override` asks
// the compiler to check that each really replaces a MonthlyBill function.
// Each returns a string literal as a std::string_view, which is safe: a
// literal lives for the whole program.
class FlatBill final : public MonthlyBill {
private:
Cents plan_charge(int gigabytes) const override; // 10.00, whatever the usage
std::string_view plan_name() const override { return "flat"; }
};
class MeteredBill final : public MonthlyBill {
private:
Cents plan_charge(int gigabytes) const override; // 0.05 per GB
std::string_view plan_name() const override { return "metered"; }
};
class TieredBill final : public MonthlyBill {
private:
Cents plan_charge(int gigabytes) const override; // first 50 GB free, then 0.08 per GB
std::string_view plan_name() const override { return "tiered"; }
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

template_form.cpp
// The template method: the same three steps for every plan. For a metered
// bill at 120 GB: the charge is 600 cents, under the 5'000 cap, and 20%
// tax makes 720, printed as 7.20.
Cents MonthlyBill::total(int gigabytes) const {
// Refuse negative usage first (throws std::invalid_argument), so no
// plan's charge ever sees it.
billing::require_usage(gigabytes);
// plan_charge is a virtual call: it runs this bill's plan. std::min
// keeps the smaller of the charge and the cap, so no bill goes over it.
const Cents net = std::min(plan_charge(gigabytes), billing::monthly_cap);
// Adds 20% tax and rounds to the nearest cent.
return billing::with_tax(net);
}

class MonthlyBill

abstract; not copyable

Data members

  • virtual Cents plan_charge(int gigabytes) const = 0; private: the step that varies
  • virtual std::string_view plan_name() const = 0; private

Member functions

  • Cents total(int gigabytes) const; non-virtual: charge, cap, tax, always in that order
  • std::string_view plan() const;

class MeteredBill final

also FlatBill, TieredBill; derives from MonthlyBill

Data members

  • Cents plan_charge(int gigabytes) const override; private: 0.05 per GB
Template Method: the base fixes the steps; each plan is a derived class

This form gets FR-1 and FR-2 right. total is not virtual, so no plan can skip the cap or the tax; a plan overrides only its own charge, and that override is private, so no caller can call it directly. Adding a plan is one small class.

Its problem is FR-3. A MeteredBill is a metered bill: the plan is the object’s class, and a C++ object’s class cannot change. If the account were a MeteredBill, changing its plan would mean destroying it and creating another, and anything else the account held, its history, its stage, must be moved across by hand.

FR-4 makes it worse. If the stage were also expressed by inheritance, every plan would need a class for every stage: TrialFlatBill, OverdueMeteredBill, and so on, 3 × 3 = 9 classes, and a fourth stage would add three more. And even then, moving from trial to active would mean replacing the object, because its class is fixed. Template Method handles one axis of variation well, and multiplies classes when there are two.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

strategy_form.hpp
// The strategy: one plan's formula, as an object of its own. The account
// holds one and can be handed another. Unlike MonthlyBill, it knows only
// the plan's charge; the cap and tax are in bill_total, below.
class PricingRule {
public:
virtual ~PricingRule() = default;
// Public this time: bill_total calls it, and a test can call it alone.
virtual Cents charge(int gigabytes) const = 0; // before the cap and tax
virtual std::string_view name() const = 0;
protected:
// Protected: only derived rules can be built or copied, and copying
// through a PricingRule& (which would copy only the base part) does not
// compile. A Flat can still be copied as a Flat.
PricingRule() = default;
PricingRule(const PricingRule&) = default;
PricingRule& operator=(const PricingRule&) = default;
};
class Flat final : public PricingRule {
public:
Cents charge(int gigabytes) const override; // 10.00, whatever the usage
std::string_view name() const override { return "flat"; }
};
class Metered final : public PricingRule {
public:
Cents charge(int gigabytes) const override; // 0.05 per GB
std::string_view name() const override { return "metered"; }
};
class Tiered final : public PricingRule {
public:
Cents charge(int gigabytes) const override; // first 50 GB free, then 0.08 per GB
std::string_view name() const override { return "tiered"; }
};
// The fixed steps, as a plain function: the rule's charge, then the cap,
// then tax. Throws std::invalid_argument for negative usage.
// Same steps and same results as MonthlyBill::total. The rule is borrowed
// through a const reference: not copied, not owned, not changed.
Cents bill_total(const PricingRule& rule, int gigabytes);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

strategy_form.hpp
// The context: an account that owns its pricing rule. The rule arrives as
// a std::unique_ptr, so the account becomes its only owner, and the rule
// is destroyed with the account or when it is replaced.
class Account final {
public:
// Throws std::invalid_argument for a null rule.
// A caller passes ownership in, as in
// Account{std::make_unique<Metered>()}.
explicit Account(std::unique_ptr<PricingRule> rule);
// The customer's choice. Throws std::invalid_argument for a null rule.
// The new rule replaces the old one, which is destroyed. If the new
// one is null, the old rule stays in place.
void change_plan(std::unique_ptr<PricingRule> rule);
// *rule_ is the rule object itself. Whatever rule is held now is used,
// so a plan change takes effect from the next bill.
Cents close_month(int gigabytes) const { return bill_total(*rule_, gigabytes); }
std::string_view plan() const { return rule_->name(); }
private:
std::unique_ptr<PricingRule> rule_; // never null, unless moved from
};

interface (abstract class) PricingRule

the strategy

Member functions

  • virtual Cents charge(int gigabytes) const = 0; before the cap and tax
  • virtual std::string_view name() const = 0;

class Metered final

also Flat, Tiered; implements PricingRule

Member functions

  • Cents charge(int gigabytes) const override; 0.05 per GB

class Account final

the context

Data members

  • std::unique_ptr<PricingRule> rule_; owned; never null (unless moved from)

Member functions

  • explicit Account(std::unique_ptr<PricingRule> rule); throws for null
  • void change_plan(std::unique_ptr<PricingRule> rule); public: the customer's choice
  • Cents close_month(int gigabytes) const; bill_total(*rule_, gigabytes)

namespace strategy_form

Functions

  • Cents bill_total(const PricingRule& rule, int gigabytes); the fixed steps, as a function
Strategy: the account holds a rule the customer chose, and can be given another

The plans are the same three formulas, and the tests check that both forms give the same total for every plan at 0, 1, 50, 51, 120, and 1200 GB. What changed:

  • FR-3 is one function. change_plan replaces the rule; the next close_month uses it. Nothing else in the account is touched. A null rule is refused, and the old rule stays.
  • The fixed steps moved into a function. bill_total does what MonthlyBill::total did: charge, cap, tax. It is still the only place those steps are written, but nothing forces a caller to use it: code that called rule.charge(gb) directly would skip the cap and the tax. Template Method’s guarantee came from the class structure; here it comes from keeping bill_total the one function that the account calls.
  • A plan can be tested alone. Metered{}.charge(120) is an ordinary call on an ordinary object.

FR-4 is a different kind of variation. Nobody outside chooses “overdue”: the account becomes overdue because a payment failed. Each stage knows which stage follows it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

state_form.hpp
// By default an event is refused; each stage overrides only the events
// it allows.
// One stage of an account's life. Each event function answers "what
// happens to an account in this stage when this event arrives?", and
// returns the stage to move to. A stage never changes itself (every
// function is const); to move on, it makes a new stage object and hands it
// back, and the Account swaps it in. Transition (above this snippet) is
// the result of closing a month: the amount due, plus the next stage or
// nullptr to stay.
class AccountState {
public:
virtual ~AccountState() = default;
virtual std::string_view name() const = 0;
// The name, unless a stage has more to say (Trial adds its count).
virtual std::string describe() const { return std::string{name()}; }
// Pure virtual: every stage must decide what closing a month means.
virtual Transition close_month(const PricingRule& plan, int gigabytes) const = 0;
// Not pure: the base version, in state_form.cpp, refuses the event by
// throwing. A stage that allows the event overrides it, and returns
// the next stage, or nullptr to stay where it is.
virtual std::unique_ptr<AccountState> payment_failed() const;
virtual std::unique_ptr<AccountState> payment_received() const;
protected:
AccountState() = default;
AccountState(const AccountState&) = default;
AccountState& operator=(const AccountState&) = default;
// Throws std::logic_error: "cannot <event> while <name>".
// [[noreturn]] promises that it never returns normally (it always
// throws), so a function that ends by calling it needs no `return`.
[[noreturn]] void refuse(std::string_view event) const;
};
// The free first months. It handles close_month only; a payment event
// during a trial is refused by the base class.
class Trial final : public AccountState {
public:
explicit Trial(int free_months); // throws unless at least 1
std::string_view name() const override { return "trial"; }
std::string describe() const override; // "trial (2 free months left)"
Transition close_month(const PricingRule& plan, int gigabytes) const override;
private:
int free_months_; // this stage's own data; it does not exist in the others
};
// A paying account: billed each month, and allows both payment events.
class Active final : public AccountState {
public:
std::string_view name() const override { return "active"; }
Transition close_month(const PricingRule& plan, int gigabytes) const override;
std::unique_ptr<AccountState> payment_failed() const override;
std::unique_ptr<AccountState> payment_received() const override;
};
// A failed payment has not been made up yet: billed with a late fee.
class Overdue final : public AccountState {
public:
std::string_view name() const override { return "overdue"; }
Transition close_month(const PricingRule& plan, int gigabytes) const override;
std::unique_ptr<AccountState> payment_failed() const override;
std::unique_ptr<AccountState> payment_received() const override;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

state_form.cpp
// A trial must have at least one free month left; "a trial with 0 free
// months" would be an active account, and is refused.
Trial::Trial(int free_months) : free_months_{free_months} {
if (free_months < 1) {
throw std::invalid_argument{"a trial needs at least one free month"};
}
}
// "trial (2 free months left)", or "month" for exactly 1. The ?: picks
// the singular or plural ending.
std::string Trial::describe() const {
return "trial (" + std::to_string(free_months_) +
(free_months_ == 1 ? " free month left)" : " free months left)");
}
// A trial month is free (due 0), whatever the plan, so the plan is not
// used and its name is left in a comment. Usage is still checked: negative
// usage throws std::invalid_argument, as in every other stage.
// `return {0, ...}` builds a Transition: due 0, and the next stage.
// This stage cannot count itself down (the function is const), so it
// makes a new Trial with one month fewer, or an Active after the last free
// month; the account replaces this stage with it.
Transition Trial::close_month(const PricingRule& /*plan*/, int gigabytes) const {
billing::require_usage(gigabytes);
if (free_months_ == 1) {
return {0, std::make_unique<Active>()}; // the trial ends by itself
}
return {0, std::make_unique<Trial>(free_months_ - 1)};
}
// The normal bill: the plan's charge, capped and taxed, by bill_total
// (which also refuses negative usage). nullptr: stay active.
Transition Active::close_month(const PricingRule& plan, int gigabytes) const {
return {strategy_form::bill_total(plan, gigabytes), nullptr};
}
// A failed payment makes an active account overdue.
std::unique_ptr<AccountState> Active::payment_failed() const {
return std::make_unique<Overdue>();
}
// Paying while active changes nothing: stay active.
std::unique_ptr<AccountState> Active::payment_received() const { return nullptr; }
// The same bill as Active, plus the late fee, which is added after tax
// (so it is not taxed). It stays overdue until a payment arrives.
Transition Overdue::close_month(const PricingRule& plan, int gigabytes) const {
return {strategy_form::bill_total(plan, gigabytes) + billing::late_fee, nullptr};
}
// Another failed payment: still overdue.
std::unique_ptr<AccountState> Overdue::payment_failed() const { return nullptr; }
// A payment clears the debt: back to active.
std::unique_ptr<AccountState> Overdue::payment_received() const {
return std::make_unique<Active>();
}

The account holds both objects, for two different reasons:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

state_form.hpp
// The account the billing system uses. It holds two objects behind two
// interfaces, for two different reasons: the plan, which the customer
// chooses (Strategy), and the stage, which moves by itself (State).
class Account final {
public:
// Starts in a trial with free_months free bills, or active if
// free_months is 0. Throws std::invalid_argument for a null plan or a
// negative number of months.
Account(std::unique_ptr<PricingRule> plan, int free_months);
void change_plan(std::unique_ptr<PricingRule> plan); // throws for null
// Each event is passed to the current stage, and the account then
// moves to whatever stage it hands back. close_month also throws
// std::invalid_argument for negative usage, and then the stage stays.
Cents close_month(int gigabytes); // returns the amount due
void payment_failed(); // throws std::logic_error in a trial
void payment_received(); // throws std::logic_error in a trial
std::string_view plan() const { return plan_->name(); }
std::string_view status() const { return state_->name(); }
std::string describe() const { return state_->describe(); }
private:
// Private: no caller can set the stage; only the events can, through
// what the stages return. Replacing state_ destroys the old stage.
void move_to(std::unique_ptr<AccountState> next); // stays put if null
// Both are never null, unless this account has been moved from.
std::unique_ptr<PricingRule> plan_; // chosen from outside
std::unique_ptr<AccountState> state_; // chosen by the states
};
How this code works: How an event moves the account's stage

Account does not decide anything about stages. For each event it does the same two things, in state_form.cpp:

  1. Ask the current stage. close_month calls state_->close_month(*plan_, gigabytes), passing the plan the customer chose. The stage returns a Transition: the amount due, and either a new stage object or nullptr. The payment events work the same way, but return only the next stage.
  2. Follow the answer. The private move_to replaces state_ with the new stage if there is one, and does nothing for nullptr. Replacing the std::unique_ptr destroys the old stage object.

That order is what makes the ownership safe. The old stage is destroyed only after its function has returned, so no stage is ever deleted while its own code is running. A refused event (a payment during a trial) throws before move_to is reached, so the stage stays as it was.

The run in main.cpp starts a metered account with 2 free months and uses 80 GB every month. A metered bill for 80 GB is 400 cents, and with tax 480 cents, or 4.80:

Event Stage before The stage returns Due Stage after
close_month(80) trial, 2 left due 0, a new Trial(1) 0.00 trial
close_month(80) trial, 1 left due 0, a new Active 0.00 active
close_month(80) active due 480, nullptr 4.80 active
payment_failed() active a new Overdue overdue
close_month(80) overdue due 480 + 500, nullptr 9.80 overdue
payment_received() overdue a new Active active
change_plan, to Flat active (the stage is not asked) active
close_month(80) active due 1200, nullptr 12.00 active

The last two rows show the two objects varying separately: the plan changed and the stage did not, and the next bill used the new plan.

interface (abstract class) AccountState

the state; payment events refused by default; every stage must handle close_month

Member functions

  • virtual Transition close_month(const PricingRule& plan, int gigabytes) const = 0; due, and the next stage
  • virtual std::unique_ptr<AccountState> payment_failed() const; next stage, or null to stay
  • virtual std::unique_ptr<AccountState> payment_received() const;

class Trial final

implements AccountState

Data members

  • int free_months_; this stage's own data

Member functions

  • Transition close_month(const PricingRule& plan, int gigabytes) const override; free; ends by itself

class Overdue final

implements AccountState (Active is similar, but bills without a fee and moves to Overdue on payment_failed)

Member functions

  • Transition close_month(const PricingRule& plan, int gigabytes) const override; bill plus late fee
  • std::unique_ptr<AccountState> payment_received() const override; back to Active

class Account final

the context: holds a strategy and a state

Data members

  • std::unique_ptr<PricingRule> plan_; never null (unless moved from); chosen from outside
  • std::unique_ptr<AccountState> state_; never null (unless moved from); chosen by the states
  • void move_to(std::unique_ptr<AccountState> next); private: only events move the stage

Member functions

  • void change_plan(std::unique_ptr<PricingRule> plan); public: the customer's choice
  • Cents close_month(int gigabytes);
  • void payment_failed();
  • void payment_received();
State: each stage handles events and returns the next stage; the account only follows

A run of the example, with the same usage every month:

Expected output
template: flat 12.00 metered 7.20 tiered 6.72
strategy: flat 12.00 metered 7.20 tiered 6.72
metered at 1200 GB is capped: 60.00
strategy: metered 7.20, then the customer picks flat 12.00
state, 80 GB a month on metered:
month 1, trial (2 free months left): 0.00 -> trial
month 2, trial (1 free month left): 0.00 -> active
month 3, active: 4.80 -> active
payment failed -> overdue
month 4, overdue: 9.80 -> overdue
payment received -> active
the customer picks flat
month 5, active: 12.00 -> active
refused: cannot record a failed payment while trial

Read the state part from the top. Two free months pass, and the trial ends by itself: no caller wrote “now become active”. A failed payment moves the account to overdue, and that month’s bill is 4.80 plus the 5.00 fee. A payment moves it back. Then the customer changes plan, and the stage does not care: the plan and the stage vary independently, which a test also checks by changing plan during a trial.

PricingRule and AccountState have the same shape: an interface, a few implementations, and a std::unique_ptr in Account. You could give the account a public set_stage and call it a strategy. Then:

  • Every caller must know the rules. The code that closes a month would have to count the free months and set “active” after the second; the payment code would have to set “overdue”. FR-4 would be spread across the program instead of living in three classes.
  • Impossible moves become possible. Nothing would stop a caller from setting “overdue” during a trial, or “trial” on an account that has paid for a year.
  • The stage’s own data has no home. Trial keeps its count of free months; in a strategy chosen from outside, the caller would have to keep it.

In the C++ code, the difference shows in access. change_plan is public, because choosing a plan is the customer’s job. move_to is private, because only the account’s own events, through the stages, may change the stage.

Question Template Method (MonthlyBill) Strategy (PricingRule) State (AccountState)
Who chooses the variation? whoever creates the object, by choosing its class a caller outside the object the states themselves, as they handle events
When can it change? never, for one object at construction, or later if the context offers a setter (here change_plan) after each event, through a private move
How is it attached? inheritance: the variant is a derived class composition: a held std::unique_ptr composition: a held std::unique_ptr, replaced by events
Where do the fixed steps live? in the base class’s non-virtual function in the context, or a function such as bill_total the context only forwards events and applies the next state; shared work such as bill_total is called by the states
Do the variants know each other? no no yes: a state creates the state that follows it
Variant-specific data members of the derived class members of the strategy members of the state; gone when the state is left
Two axes of variation at once one class per combination hold two strategies a state and a strategy, as Account does
Cost of one more variant one derived class one class; callers can use it at once one class, plus edits to the states that move to it
Choosing by who changes the varying part, and when
Text description of the diagram

A decision flowchart. The first question: can the varying part change while the object lives? If not, ask whether the fixed steps must be enforced, with only a step or two varying. If so, use a Template Method. If not, use a Strategy chosen at construction, or a template parameter. If the varying part can change while the object lives, ask who changes it. If a caller outside changes it, use a Strategy. If the object itself changes it, as events happen, use a State.

Diagram source (Mermaid)
flowchart TD
Q1{"Can the varying part change<br/>while the object lives?"}
Q1 -- "no" --> Q2{"Must the fixed steps<br/>be enforced, with only<br/>a step or two varying?"}
Q2 -- "yes" --> TM["Template Method"]
Q2 -- "no" --> S1["Strategy chosen at construction,<br/>or a template parameter"]
Q1 -- "yes" --> Q3{"Who changes it?"}
Q3 -- "a caller outside" --> S2["Strategy"]
Q3 -- "the object itself,<br/>as events happen" --> ST["State"]
  1. Can the varying part change while the object lives? If not, it can be bound when the object is created. Template Method binds it by class; a Strategy passed to the constructor and never replaced binds it by object; a template parameter binds it at compile time, as the Strategy page’s three ways to write a strategy shows.
  2. If it cannot change: must the steps be enforced? Template Method’s real strength is the non-virtual function that fixes the order. If there are only one or two varying steps, and the variants are few and stable, it is the shortest design. If the variants should be tested alone, or may combine with another axis later, prefer a Strategy even though it never changes.
  3. If it can change: who changes it? A caller choosing a behaviour is Strategy. The object moving through stages because of what happened to it is State.
  • The variants are one-liners with no data of their own. The three plans here are each one line of arithmetic. If they will stay that way, an enum class Plan and a switch in bill_total, or a std::function, would be shorter. The classes earn their place when plans grow data of their own, such as a contract’s end date or a per-customer allowance. Be honest about which is true.
  • The stages are few and the rules are uniform. Three stages and three events could be a switch on an enum class Stage. State pays off when stages have their own data (Trial’s free months), when refusals differ by stage, and when stages are added over time. For many states with uniform rules, a transition table is often clearer, as the State page explains.
  • Nothing varies yet. One plan does not need a PricingRule interface. Add it when the second plan is real.
  • A fourth plan, “family”, with an allowance per member. One new PricingRule class with its own data. No stage changes, and no other plan changes. In the Template Method form, one new derived class.
  • A new stage: suspended, after three failed payments. Overdue gains a count of failed payments, its own data. Active::payment_failed returns Overdue{1}; Overdue::payment_failed returns Overdue{count + 1}, or Suspended on the third. Suspended overrides close_month to refuse. No plan changes. With an enum and a switch, the count would have to live in the account, meaningful in one stage only.
  • A new fixed step: a 1% card-processing surcharge on every bill. One change in bill_total (or MonthlyBill::total), and every billed month gets it (the late fee, added afterwards, does not). This is the payoff of keeping the fixed steps in one place in either form.

Exercise: Choose for four scenarios

For each scenario, choose Template Method, Strategy, State, a combination, or something simpler. Say who chooses the variation and when it can change.

  1. A text editor checks spelling in a language the user picks in the settings. The user may change it at any time, and the editor should check the open document again with the new language.
  2. A vending machine is idle, has coins, is dispensing, or is out of stock. What “insert coin” and “press button” do depends on which of these it is in, and each action can move it to another.
  3. Every export the program writes must have a header, a body, and a checksum footer, in that order. Only the body’s format differs between the CSV and JSON exporters, and an exporter never changes format.
  4. A traffic-light controller cycles through red, green, and amber, and each light’s timing depends on a timing plan, day or night, that a city operator switches twice a day.
Show the explained answer

1. Strategy. The user, from outside, chooses the language, and can change it at any time. The editor holds a SpellChecker behind an interface (or a dictionary object) and replaces it when the setting changes. Languages do not know each other or choose the next language.

2. State. Nobody outside picks “dispensing”; the machine moves there because a button was pressed with enough coins inserted. Each stage decides what an action does and which stage follows, and “has coins” carries its own data, the amount inserted. With four stages and two actions, an enum class and a switch is a fair alternative; State earns its place if the stages grow their own data and rules.

3. Template Method. The order of the steps is the rule that must not be broken, only the body varies, and the variant is fixed for each exporter. A base class with a non-virtual write that writes the header, calls a private virtual write_body, and adds the checksum enforces the order. If formats later combined with another axis, such as compression, switch the body format to a Strategy.

4. Both: State for the lights, Strategy for the timing. The lights move by themselves, red to green to amber to red, as timers expire: State (or, with three lights and one rule, an enum class and a switch). The timing plan is chosen from outside by the operator and can change at any time: Strategy. The controller holds both, as Account holds a stage and a plan, and the current light asks the timing plan how long it lasts.