模板方法模式,定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
AbstractClass实现了一个模板方法,定义了算法的骨架,具体子类将重定义PrimitiveOperation以实现一个算法的步骤。
ConcreteClass实现PrimitiveOperation以完成算法中与特定子类相关的步骤。每一个AbstractClass可以有多个ConcreteClass与之对应。
参照大话设计模式上,用C++对其进行重新实现,代码如下:
//抽象父类
#ifndef __TEST_PAPER_H__
#define __TEST_PAPER_H__
#include "stdio.h"
class TestPaper
{
public:
TestPaper() {}
virtual ~TestPaper() {}
void TestQuestion1()//d
{
printf("计算机能直接执行的程序是[%s]\nA.源程序 B.目标程序 C.汇编程序 D.可执行程序\n", Answer1());
}
void TestQuestion2()//a
{
printf("C源程序中不能表示的数制是[%s]\nA.二进制 B.八进制 C.十进制 D.十六进制\n", Answer2());
}
void TestQuestion3()//a
{
printf("[%s]是构成C语言程序的基本单位。\nA.函数 B.过程 C.子程序 D.子例程\n", Answer3() );
}
virtual char* Answer1() = 0;
virtual char* Answer2() = 0;
virtual char* Answer3() = 0;
};
#endif // !__TEST_PAPER_H__
#ifndef __TEST_PAPERA_H__
#define __TEST_PAPERA_H__
#include "TestPaper.h"
class TestPaperA : public TestPaper
{
public:
virtual char* Answer1()
{
return "D";
}
virtual char* Answer2()
{
return "A";
}
virtual char* Answer3()
{
return "A";
}
};
#endif // !__TEST_PAPERA_H__
#ifndef __TEST_PAPERB_H__
#define __TEST_PAPERB_H__
#include "TestPaper.h"
class TestPaperB : public TestPaper
{
public:
virtual char* Answer1()
{
return "D";
}
virtual char* Answer2()
{
return "A";
}
virtual char* Answer3()
{
return "A";
}
};
#endif // !__TEST_PAPERB_H__
//客户端代码
#include "windows.h"
#include "tchar.h"
#include "TestPaperA.h"
#include "TestPaperB.h"
int _tmain(int argc, TCHAR* argv[])
{
printf("Mr Wang的试卷:\n");
TestPaper *studentA = new TestPaperA();
studentA->TestQuestion1();
studentA->TestQuestion2();
studentA->TestQuestion3();
if (studentA)
{
delete studentA;
studentA = NULL;
}
printf("\n\n");
printf("Mrs Yu的试卷:\n");
TestPaper *studentB = new TestPaperB();
studentB->TestQuestion1();
studentB->TestQuestion2();
studentB->TestQuestion3();
if (studentB)
{
delete studentB;
studentB = NULL;
}
}
运行结果如下: