First, Introduction
1. The template method pattern defines an algorithm skeleton in an operation, and some steps are deferred to the subclass middle age. The template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.
2. The template method pattern is to put some common steps in the base class, and put different links in the subclass, in order to reduce the reuse of code.
3, for example: The test copy the topic and do the answer, the teacher copy of the topic for each student is certainly the same, but each student's answer is different.
Second, C + + code
1 //Template method mode. CPP: The entry point that defines the console application. 2 //3 4#include"stdafx.h"5#include <iostream>6 using namespacestd;7 8 classShijuan9 {Ten Public: One Shijuan () {} A~Shijuan () {} - voidQuestion1 () - { thecout<<"1. How many campuses are there in Hohai university? "<<endl<<"A 1 B 2 C 3 D 4"<<Endl; -cout<<"I choose to be"<<answer1 () <<Endl; - } - Virtual CharAnswer1 () =0; + voidQuestion2 () - { +cout<<"2. How many colleges are there in Changzhou campus of Hohai University? "<<endl<<"A 1 B 2 C 3 D 4"<<Endl; Acout<<"I choose to be"<<answer2 () <<Endl; at } - Virtual CharAnswer2 () =0; - }; - classStudent1: PublicShijuan - { - Virtual CharAnswer1 () in { - return 'C'; to } + Virtual CharAnswer2 () - { the return 'C'; * } $ };Panax Notoginseng - classStudent2: PublicShijuan the { + Virtual CharAnswer1 () A { the return 'A'; + } - Virtual CharAnswer2 () $ { $ return 'B'; - } - }; the - int_tmain (intARGC, _tchar*argv[])Wuyi { the //1 of the students ' answer results -Shijuan *s1=NewStudent1 (); Wucout<<"I am a student 1, here is my answer to the results"<<Endl; -S1->Question1 (); AboutS1->Question2 (); $ //2 of the students ' answer results -Shijuan *s2=NewStudent2 (); -cout<<"I am a student 2, here is my answer to the results"<<Endl; -S2->Question1 (); AS2->Question2 (); + return 0; the}
Template method Mode