Overview

classDiagram

class AbstractClass {
    +templateMethod()
    +step1()*
    +step2()
    +step3()*
    +step4()*
}

class ConcreteClass1 {
    +step3()
    +step4()
}

class ConcreteClass2 {
    +step1()
    +step2()
    +step3()
    +step4()
}

AbstractClass <|-- ConcreteClass1
AbstractClass <|-- ConcreteClass2

In the templateMethod() function, it just literally executes stepX() step by step. So in ConcreteClassX, by rewriting stepX() method, we can replace certain components without affecting other components.

与 Strategy 设计模式的区别

Strategy 设计模式的被调用者是 Context,而 Context 里的 Strategy 可以被替换.因此总的来说,Strategy 设计模式依靠组合、可替换、运行时选择

而 Template Method 的实际被调用者是 ConcreteClassX,即 Template Method 的具体实现.而 Template Method 的步骤流程其实是固定的,所以 Template Method 的本质是依靠继承、固定流程、步骤可变完成.