模板方法模式,定义一个操作中的算法骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
模板发放模式特点
模板方法模式就是通过把不变行为搬移到超类,去除子类中的重复代码来体现它的优势。
模板方法模式就是提供了一个很好的代码复用平台。当不变的和可变的行为在方法的子类实现中混合在一起的时候,不变的行为就会在子类中重复出现。我们通过模板方法模式把这些行为搬移到单一的地方,这样就帮助子类摆脱重复的不变行为的纠缠。
#include <iostream> using namespace std; class Text //模板类 { public: void TextQuestion1() //问题1 { cout<<"“大煮干丝”是哪个菜系的代表菜之一( )。"<<endl<<"A四川菜系 B山东菜系 C广东菜系 D淮扬菜系"<<endl; cout<<"答案:"<<TextAnswer1()<<endl; } virtual string TextAnswer1() //问题1的答案 虚函数 { return ""; } void TextQuestion2() //问题2 { cout<<"红茶属于( )茶。"<<endl<<"A半发酵 B发酵 C不发酵 D微发酵"<<endl; cout<<"答案:"<<TextAnswer2()<<endl; } virtual string TextAnswer2() //问题2的答案 虚函数 { return ""; } }; class TextPaperA : public Text //学生A的答卷 { public: string TextAnswer1() //学生A对第一题的答案 { return "A"; } string TextAnswer2() //学生A对第二题的答案 { return "D"; } }; class TextPaperB : public Text //学生B的答卷 { public: string TextAnswer1() //学生B对第一题的答案 { return "B"; } string TextAnswer2() //学生B对第二题的答案 { return "A"; } }; int main() { cout<<"学生A的答卷:"<<endl; Text* student1 = new TextPaperA; student1->TextQuestion1(); student1->TextQuestion2(); cout<<"\n学生B的答卷:"<<endl; Text* student2 = new TextPaperB; student2->TextQuestion1(); student2->TextQuestion2(); return 0; } 显示效果: