Template...其實主要闡述Abstract Class的感覺
把壹些共通性的資訊或方法保留在parent class,並保留了實做變更的彈性給與繼承的子類別
Intent (意圖)-
定義出function or 演算法的骨架出來,並且把部分的細節推遲放到子類別中再進行,樣版模式讓子類別
重新定義funciton內涵並避免去破壞演算法的結構。
Motivation(動機)-
有時候我們會想要去定義一連串的method運作順序,但在特定的情況下會允許子類別去覆寫部分的method內容。
參考一下以下的class diagram
而在開啟文件的功能中,也許原本已經有設計了一連串的相應流程,如下說明
假想一下,當文件類別多了好幾種 ,像是PlainTextDocument / HtmlDcoument...
那麼我們就應該會來改變一下OpenDocument的做法,只是應該大部分的開檔過程中的做法是幾乎一樣的,
如果在眾多的子類別中看到很多一樣的method,就應該建議選擇將method抽離到父類別來,
並修改程式運作流程,使的在各種特異的子類別中專屬的method flow or definition得以繼續運作
Applicability(適用性)-到底何時該來使用template pattern ?
- 將要設計的method當中不變性的部分設計在父類別中,並將具有變化性的部分保留到子類別予以覆寫設計
- 將常用、通用的程式碼集中縮小在同一個class裡面,這也是屬於重構的一部分
- To control how subclasses extend superclass operations. You can define atemplate method that calls "hook" operations at specific points, therebypermitting extensions only at those points.
那既然說到要把method留到子類別中進行覆寫與設計,就要參考看看以下的建議了
- Operations which must be overridden by a subclass should be made abstract
- If the template method itself should not be overridden by a subclass, it should be made final
- To allow a subclass to insert code at a specific spot in the operation of the algorithm, insert “hook” operations into the template method. These hook operations may do nothing by default.
- Try to minimize the number of operations that a subclass must override,otherwise using the template method becomes tedious for the developer
- In a template method, the parent class calls the operations of a subclass and not the other way around. This is an inverted control structure that'ssometimes referred to as "the Hollywood principle," as in, "Don't call us,we'll call you".
在上面第3點提到的 hook method,用來做為中斷流程的客製化起點,可以看看下面這例子
ex: Class Manufacturing提供了兩個不同的method分別做不同的biz alogrithm
然而在其子類別MyManufacturing當中,想要去改變makePart()的呼叫程式順序,中間需要插入額外的判斷時,可以使用以下方式
ex: 在子類別中覆寫operation2,先執行想要額外運作的code,再呼叫super.operation2()
一但我們有好多個子類別都有類似的情況時,就可以再做一些調整,把common method 給hook到 super class
並且在父類別中先保留空白的hook method,讓各個子類別自行運用
沒有留言:
張貼留言