Template Method Pattern

這個 pattern 是用來建立一個 algorithm 的 template。在一個 method 中定義 algorithm 的骨架,其中的小步驟定義在 derived class。可以在不改變 algorithm 架構的狀況下改變其中某些步驟的做法。

UML

Template Method

template method 定義了 algorithm 的骨架,derived class 藉由 override 其中的步驟 function 改變 algorithm 的行為。

在 base class 中可以定義共用的 operation。有些 operation 在 algorithm 概念上是 derived class 一定要 implement 的,C++ 裡可用 pure virtual function。通常 base class 會有一份 hook 的 implement,derived class 可以選擇性 override hook,依據 hook 在 template method 裡的使用,override hook 可能影響 algorithm 的行為,例如做或不做某些步驟。

相關 pattern

Factory Method pattern 是 Template Method 的特殊版,用來生 object。

Strategy 跟 Template Method 都用來封裝 algorithm,不過不太一樣。Strategy 是各個 derived class 自己完整 implement algorithm,Template Method 則是先訂好一個 “template”,其中的步驟是可以被改變的。

應用

很多 UI framework,例如 Java 的 UI framework 跟 Qt,都有 paint() 之類的 painting function 以及 event handling function(例如處理 mouse event)就是使用 Template Method pattern。framework 已經決定何時會 call 這些 function,而 user 寫的 UI component 則依據需要 override 這些 function 決定實際上要做什麼事,如畫什麼東西、按滑鼠時要做什麼等等。