模板方法模式(Template Method)
模板方法模式,定义一个操作中的算法的骨架,而将一些步骤迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤。
代码
我们以一个试卷问答的程序来阐述模板方法模式:
1.代码如下:
试卷基类
using System;
namespace TemplateMethod
{
//试题类
public class TestPaper
{
//问题1
public void TestQuestion1(){
Console.WriteLine ("问题1");
Console.WriteLine ("答案:" + Answer1 ());
}
//问题2
public void TestQuestion2(){
Console.WriteLine ("问题2");
Console.WriteLine ("答案:" + Answer2 ());
}
//问题3
public void TestQuestion3(){
Console.WriteLine ("问题3");
Console.WriteLine ("答案:" + Answer3 ());
}
//答案1
protected virtual string Answer1(){
return "";
}
//答案2
protected virtual string Answer2(){
return "";
}
//答案3
protected virtual string Answer3(){
return "";
}
}
}
具体的试卷类
using System;
namespace TemplateMethod
{
public class TestPaperA:TestPaper
{
protected override string Answer1(){
return "b";
}
protected override string Answer2(){
return "c";
}
protected override string Answer3(){
return "a";
}
}
}
using System;
namespace TemplateMethod
{
public class TestPaperB:TestPaper
{
protected override string Answer1(){
return "c";
}
protected override string Answer2(){
return "a";
}
protected override string Answer3(){
return "a";
}
}
}
2.客户端代码如下:
客户端代码
using System;
namespace TemplateMethod
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("学生甲抄的试卷:");
TestPaper studentA = new TestPaperA ();
studentA.TestQuestion1 ();
studentA.TestQuestion2 ();
studentA.TestQuestion3 ();
Console.WriteLine ("学生乙抄的试卷:");
TestPaper studentB = new TestPaperB ();
studentB.TestQuestion1 ();
studentB.TestQuestion2 ();
studentB.TestQuestion3 ();
}
}
}
3.运行结果