Mr. Latte


Lesson 9 of 13

Template Method: Fix the Sequence, Vary a Step

Reading, cleaning, and exporting data may follow a stable order while one cleanup rule changes. Template Method keeps the shared procedure in a parent class and lets subclasses implement selected steps.

Keep the stable sequence in one place

class TextJob:
    def run(self, text):
        cleaned = text.strip()
        return self.transform(cleaned)
    def transform(self, text):
        raise NotImplementedError

class UppercaseJob(TextJob):
    def transform(self, text):
        return text.upper()

print(UppercaseJob().run("  latte  "))

The output is LATTE. The run method strips whitespace, transforms, and returns the result. UppercaseJob supplies only transform. Optional extension points can use hooks with default implementations.

Growing checks for subclass types inside the shared procedure can signal an unsuitable abstraction. Parent changes can affect many children. In Python, preserving the agreement not to override run requires review or additional design.

Compare Strategy

Strategy delegates to another object or function through composition. Template Method varies steps through inheritance. Strategy often suits changing algorithms at runtime; Template Method can suit controlled extension of a stable sequence.

Check your understanding

You want to provide a different cleanup function on every run. Must you keep creating subclasses?

Show explanation

No. Passing a strategy function may be simpler. First establish a reason to manage the procedure through an inheritance hierarchy.

Looking for a product partner? Founders, teams, businesses: from problem framing to launch.