模板方法模式
定义:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
举例:学生甲和学生乙抄写的试卷非常类似,除了答案不同之外,其余的题目完全相同。如果老师要更改题目,意味着两个人的试卷都需要更改,这样很容易出错。如何做才能使错误降低到最少,则需要模板方法模式。
试卷代码如下:
<span style="font-size:18px;">namespace _10._3_提炼代码
{
class TestPaper
{
//试题1
public void TestQuestion1()
{
Console.WriteLine("试题1");
Console.WriteLine("答案:"+Answer1());
}
protected virtual string Answer1()
{
return"";
}
//试题2
public void TestQuestion2()
{
Console.WriteLine("试题2");
Console.WriteLine("答案:"+Answer2());
}
protected virtual string Answer2()
{
return"";
}
//试题3
public void TestQuestion3()
{
Console.WriteLine("试题3");
Console.WriteLine("答案:"+Answer3());
}
protected virtual string Answer3()
{
return"";
}
}
//学生甲抄的试卷
class TestPaperA : TestPaper
{
protected override string Answer1()
{
return "b";
}
protected override string Answer2()
{
return "c";
}
protected override string Answer3()
{
return "a";
}
}
//学生乙抄的试卷
class TestPaperB : TestPaper
{
protected override string Answer1()
{
return "c";
}
protected override string Answer2()
{
return "a";
}
protected override string Answer3()
{
return "a";
}
}
class Program
{
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();
Console.Read();
}
}
}
</span>运行结果如下:
模板方法模式包含如下两个角色:
(1) AbstractClass(抽象类):在抽象类中定义了一系列基本操作(PrimitiveOperations),这些基本操作可以是具体的,也可以是抽象的,每一个基本操作对应算法的一个步骤,在其子类中可以重定义或实现这些步骤。同时,在抽象类中实现了一个模板方法(Template Method),用于定义一个算法的框架,模板方法不仅可以调用在抽象类中实现的基本方法,也可以调用在抽象类的子类中实现的基本方法,还可以调用其他对象中的方法。
(2) ConcreteClass(具体子类):它是抽象类的子类,用于实现在父类中声明的抽象基本操作以完成子类特定算法的步骤,也可以覆盖在父类中已经实现的具体基本操作。
原文:http://blog.csdn.net/u010104750/article/details/40661257