您的位置:首页 > 编程语言 > C语言/C++

(原創) 我的Design Pattern之旅[2]:Template Method Pattern (OO) (Design Pattern) (C++)

2007-03-31 15:24 771 查看
Abstract
template method pattern是我學到第二個pattern,算是一個很容易理解的pattern,但卻非常的實用。

Intent
對於operation,只先定義好演算法的輪廓,某些步驟則留給子類別去填補,以便在不改變演算法整體架構的情況下讓子類別去精鍊某些步驟。

其UML表示法

10#include <iostream>
11
12using namespace std;
13
14
25
32
39
46Making Teaboil some water
steep tea in boiling water
pour tea in cup
add lemon

Making Coffeeboil some water
brew coffee in boiling water
pour coffee in cup
add sugar and milk.

感謝Quark提供template版本的template method寫法

1#include <iostream>
2
3using namespace std;
4
5template<typename T>
6
23
31
39

Remark
strategy和template method目的相同,皆對『新需求』的不同演算法提供『擴充』的機制,但手法卻不同,strategy採用object的方式,利用delegation改變algorithm,而template method則採用class的繼承方式來改變algorithm,由於用到的是class的inheritance,所以在compile-time就已經決定要override的algorithm,run-time就無法再改了,但strategy用的是object手法,所以在run-time還可以透過換object改變algorithm。

GoF的原文如下

Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.

See Also
(原創) 我的Design Pattern之旅[1]:Strategy Pattern (初級) (Design Pattern) (C++) (OO C++) (Template C++)

Reference
GoF,Design Patterns,Addison Weseley Longman,1995
Scott Meyers,Effective C++ 3/e Item 35,Addison Wesley,2005
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: