C++设计模式--模板方法模式

// TemplateMethodPattern.cpp : 定义控制台应用程序的入口点。
//通过此例程了解设计模式里的“模板方法模式”

//模板方法模式:定义一个操作中的算法的骨架,而将一些步骤延迟待子类中,模板方法模式使得子类可以不改变一个算法的结构
//即可定义该算法的某些特定步骤

//下面采用《大话设计模式》里的学生考试做选择题的例子解释这一模式
//老师给每个学生发试卷,试卷上的题目都相同,
//发给学生后,让学生做题,考试结束后,对于这些试卷,唯有答案可能不同
//对于此情形,试卷相当于模板,而学生的答案相当于方法



#include "stdafx.h"
#include <process.h>
#include <iostream>
using namespace std;
 
//试卷模板
class TestPaper
{
public:
 void TestQuestion1()
 {
  cout<<"杨过得到玄铁,后来给了郭,炼成倚天剑,请问玄铁可能为() a 球磨矿, b 马口铁 c 高速合金钢, d 碳素纤维"<<endl;
  cout<<endl;
  cout<<"答案是:"<<answer1()<<endl;
  cout<<endl;
 }
 void TestQuestion2()
 {
  cout<<"杨过,程英,陆无双铲除了情花,造成了,() a 这种植物不再害人, b 使一种珍惜植物灭绝 c 破坏了生态平衡, d 造成该地区沙漠化"<<endl;
  cout<<endl;
  cout<<"答案是:"<<answer2()<<endl;
  cout<<endl;
 }
 void TestQuestion3()
 {
  cout<<"蓝凤凰致使华山师徒,桃谷六仙呕吐不止,如果你是医生,请问你要用什么药() a 阿斯匹林, b 牛黄解毒片 c 氲气, d 牛奶"<<endl;
  cout<<endl;
  cout<<"答案是:"<<answer3()<<endl;
  cout<<endl;
 }
 virtual ~TestPaper()
 {
 }
 TestPaper()
 {
 }
public:
 virtual char answer1()=0;
 virtual char answer2()=0;
 virtual char answer3()=0;
};
 
//学生A的试卷

class TestPaperA:public TestPaper
{
public:
 TestPaperA()
 {
 }
 ~TestPaperA()
 {
 }
public:
 char answer1(){return 'C';}
 char answer2(){return 'C';}
 char answer3(){return 'C';}
};
 
 
//学生B的试卷
class TestPaperB:public TestPaper
{
public:
 TestPaperB()
 {
 }
 ~TestPaperB()
 {
 }
public:
 char answer1()
 {
  return 'A';
 }
 char answer2()
 {
  return 'B';
 }
 char answer3()
 {
  return 'A';
 }
};
 
 

int main()
{
 cout<<"-------------------学生A的试卷-------------------"<<endl<<endl;
 TestPaper *pStuA=new TestPaperA();
 pStuA->TestQuestion1();
 pStuA->TestQuestion2();
 pStuA->TestQuestion3();
 cout<<endl<<endl;
 cout<<"------------------学生B的试卷------------------"<<endl<<endl;
 TestPaper *pStuB=new TestPaperB();
 pStuB->TestQuestion1();
 pStuB->TestQuestion2();
 pStuB->TestQuestion3();
 system("pause");
 return 0;
}


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值