ISO C++ by Template
1/**//*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : DP_StrategyPattern_template.cpp
5Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6Description : Demo how to use Strategy Pattern by template
7Release : 03/31/2007 1.0
8*/
9#include <iOStream>
10
11using namespace std;
12
13template <typename T>
14class Grapher {
15private:
16 T _drawTemplate;
17
18public:
19 void drawShape() const;
20};
21
22template<typename T>
23void Grapher<T>::drawShape() const {
24 _drawTemplate.draw();
25}
26
27class Triangle {
28public:
29 void draw() const;
30};
31
32void Triangle::draw() const {
33 cout << "Draw Triangle" << endl;
34}
35
36class Circle {
37public:
38 void draw() const;
39};
40
41void Circle::draw() const {
42 cout << "Draw Circle" << endl;
43}
44
45class Square {
46public:
47 void draw() const;
48};
49
50void Square::draw() const {
51 cout << "Draw Square" << endl;
52}
53
54int main() {
55 Grapher<Square> grapher;
56 grapher.drawShape();
57
58 Grapher<Circle> grapher2;
59 grapher2.drawShape();
60}
執行結果
Draw Square
Draw Circle
同樣是實現多型,Design Pattern的用的是OOP的interface + dynamic binding技術,這是在run-time下完成,優點是在run-time動態改變,缺點是速度較慢;GP用template技術,這是在compile-time下完成,優點是速度較快,缺點是無法在run-time動態改變,由於template方式不需interface,所以整個程式看不到interface,也由於無法run-time改變,所以沒有setShape(),而16行的
T _drawTemplate;
也只是object而非pointer,因為不需run-time的多型,也非function pointer。
46行
Grapher<Square> grapher;
也只能在直接指定strategy,無法動態再改變。
C# 2.0也提供泛型了,所以C#也可以用Generics實現Strategy Pattern。