,定義一個操作中的算法的骨架,而将一些步驟延遲到子類中。模闆方法是的子類可以不改變一個算法的結構即可重定義該算法的某些特定的步驟。
模闆方法模式

“模闆方法是通過把不變形為搬移到超類,去除子類中重複代碼來展現它的優勢。”
“既然用了繼承,并且肯定這個繼承有意義,就應該要成為子類的模闆,所有重複的代碼都應該要上升到父類去,而不是讓每個子類都去重複。”
“我們要完成在某一細節層次一緻的一個過程或一些列步驟,但其個别步驟在更詳細的層次上的實作可能不同時,我們通常考慮模闆方法模式來處理。”
抄寫試卷例子的實作
1 #include <iostream>
2 #include <string>
3
4 using std::cout;
5 using std::endl;
6 using std::string;
7
8 //金庸小說考題試卷
9 class TestPater
10 {
11 public:
12 void TestQuestion1()
13 {
14 cout<<"楊過得到,後來給了郭靖,煉成倚天劍、屠龍刀的玄鐵是[]\
15 a.球磨鑄鐵 b.馬口鐵 c.告訴合金鋼 d.碳素纖維"<<endl;
16 cout<<"答案:"<<Answer1()<<endl<<endl;
17 }
18 void TestQuestion2()
19 {
20 cout<<"楊過、程英、陸無雙鏟除了情花,造成[]\
21 a.這種植物不再害人 b.是一種珍稀物種滅絕 c.破壞了那個生物圈的生态平衡 d.造成該地區沙漠化"<<endl;
22 cout<<"答案:"<<Answer2()<<endl<<endl;
23 }
24 void TestQuestion3()
25 {
26 cout<<"藍鳳凰緻使華山師徒、桃谷六仙嘔吐不止,如果你是大夫,會給他們開什麼藥[]\
27 a.阿司匹林 b.牛黃解毒片 c.氟哌酸 d.讓他們喝大量的生牛奶 e.以上全不對"<<endl;
28 cout<<"答案:"<<Answer3()<<endl<<endl;
29 }
30
31 virtual string Answer1()
32 {
33 return "";
34 }
35 virtual string Answer2()
36 {
37 return "";
38 }
39 virtual string Answer3()
40 {
41 return "";
42 }
43 };
44
45 //學生甲抄的試卷
46 class TestPaterA : public TestPater
47 {
48 public:
49 string Answer1()
50 {
51 return "a";
52 }
53 string Answer2()
54 {
55 return "b";
56 }
57 string Answer3()
58 {
59 return "c";
60 }
61 };
62
63 //學生乙抄的試卷
64 class TestPaterB : public TestPater
65 {
66 public:
67 string Answer1()
68 {
69 return "c";
70 }
71 string Answer2()
72 {
73 return "b";
74 }
75 string Answer3()
76 {
77 return "a";
78 }
79 };
80
81 int main()
82 {
83 cout<<"學生甲抄的試卷:"<<endl;
84 TestPater* studentA = new TestPaterA();
85 studentA->TestQuestion1();
86 studentA->TestQuestion2();
87 studentA->TestQuestion3();
88
89 cout<<"學生乙抄的試卷:"<<endl;
90 TestPater* studentB = new TestPaterB();
91 studentB->TestQuestion1();
92 studentB->TestQuestion2();
93 studentB->TestQuestion3();
94
95 return 0;
96 }
模闆方法模式C++代碼
2
3 using std::cout;
4 using std::endl;
5
6 class AbstractClass
7 {
8 public:
9 void TemplateMethod() //給出了邏輯的骨架,而邏輯的組成是一些抽象操作,它們都推遲到子類實作
10 {
11 PrimitiveOperation1();
12 PrimitiveOperation2();
13 cout<<"公共操作"<<endl;
14 }
15 virtual void PrimitiveOperation1() = 0;
16 virtual void PrimitiveOperation2() = 0;
17 };
18
19 class ConcreteClassA : public AbstractClass
20 {
21 public:
22 void PrimitiveOperation1()
23 {
24 cout<<"具體類A方法1實作"<<endl;
25 }
26 void PrimitiveOperation2()
27 {
28 cout<<"具體類A方法2實作"<<endl;
30 };
31
32 class ConcreteClassB : public AbstractClass
33 {
34 public:
35 void PrimitiveOperation1()
37 cout<<"具體類B方法1實作"<<endl;
39 void PrimitiveOperation2()
41 cout<<"具體類B方法2實作"<<endl;
45 int main()
46 {
47 AbstractClass* c;
48
49 c = new ConcreteClassA();
50 c->TemplateMethod();
51
52 delete c;
53
54 c = new ConcreteClassB();
55 c->TemplateMethod();
56
57 return 0;
58 }