一、简介
1、模板方法模式定义一个操作中的算法骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
2、说白了模板方法模式就是将一些通用的步骤放在基类中,而将不同的环节放在子类中,以减少代码的重用。
3、举例:考试中抄写题目并做答案,老师抄的题目对于每位同学来说肯定是相同的,但是每位同学的答案是不同的。
4、UML图
5、所属类别:行为型
二、C++代码
1 // 模板方法模式.cpp : 定义控制台应用程序的入口点。
2 //
3
4 #include "stdafx.h"
5 #include<iostream>
6 using namespace std;
7
8 class Shijuan
9 {
10 public:
11 Shijuan(){}
12 ~Shijuan(){}
13 void question1()
14 {
15 cout<<"1、河海大学有几个校区?"<<endl<<"A 1 B 2 C 3 D 4"<<endl;
16 cout<<"我选择的是"<<answer1()<<endl;
17 }
18 virtual char answer1()=0;
19 void question2()
20 {
21 cout<<"2、河海大学常州校区有几个学院?"<<endl<<"A 1 B 2 C 3 D 4"<<endl;
22 cout<<"我选择的是"<<answer2()<<endl;
23 }
24 virtual char answer2()=0;
25 };
26 class Student1:public Shijuan
27 {
28 virtual char answer1()
29 {
30 return 'C';
31 }
32 virtual char answer2()
33 {
34 return 'C';
35 }
36 };
37
38 class Student2:public Shijuan
39 {
40 virtual char answer1()
41 {
42 return 'A';
43 }
44 virtual char answer2()
45 {
46 return 'B';
47 }
48 };
49
50 int _tmain(int argc, _TCHAR* argv[])
51 {
52 //学生1的答题结果
53 Shijuan *s1=new Student1();
54 cout<<"我是学生1,下面是我的答题结果"<<endl;
55 s1->question1();
56 s1->question2();
57 //学生2的答题结果
58 Shijuan *s2=new Student2();
59 cout<<"我是学生2,下面是我的答题结果"<<endl;
60 s2->question1();
61 s2->question2();
62 return 0;
63 }