一、模板方法模式
- AbstractClass 抽象类。
abstract class AbstractClass
{
//一些抽象行为,放到子类中去实现
public abstract void PrimitiveOperation1();
public abstract void PrimitiveOperation2();
//模板方法,给出了逻辑的股价,而逻辑的组成是一些相应的抽象操作,它们都推迟到子类中去实现
public void TemplateMethod()
{
PrimitiveOperation1();
PrimitiveOperation2();
Console.WriteLine("");
}
}
- ConcreteClass 实现父类所定义的一个或多个抽象方法。每一个 AbstractClass 都可以有多个 ConcreteClass 与之对应,而每一个 ConcreteClass 都可以给出这些抽象方法的不同实现,从而使得顶级逻辑的实现各不相同。
class ConcreteClassA: AbstractClass
{
public override void PrimitiveOperation1()
{
Console.WriteLine("A 方法1实现");
}
public override void PrimitiveOperation2()
{
Console.WriteLine("A 方法2实现");
}
}
class ConcreteClassB: AbstractClass
{
public override void PrimitiveOperation1()
{
Console.WriteLine("B 方法1实现");
}
public override void PrimitiveOperation2()
{
Console.WriteLine("B 方法2实现");
}
}
二、模板方法模式的特点
是通过把不变的行为放到抽象类中,取出子类中的重复代码来体现它的优势。
三、举例
using System;
namespace Factory1
{
class TestPaper{
public void TestQuestion1(){
Console.WriteLine("maybe TestQuestion1 [ ]a.A b.B c.C d.D");
Console.WriteLine("answer: " + Answer1());
}
public void TestQuestion2()
{
Console.WriteLine("maybe TestQuestion2 [ ] a.A b.B c.C d.D");
Console.WriteLine("answer: " + Answer2());
}
public void TestQuestion3()
{
Console.WriteLine("maybe TestQuestion3 [ ] a.A b.B c.C d.D");
Console.WriteLine("answer: " + Answer3());
}
protected virtual string Answer1()
{
return "";
}
protected virtual string Answer2()
{
return "";
}
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 "b";
}
protected override string Answer3()
{
return "a";
}
}
//调用
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("studentA");
TestPaper studentA = new TestPaperA ();
studentA.TestQuestion1 ();
studentA.TestQuestion2 ();
studentA.TestQuestion3 ();
TestPaper studentB = new TestPaperB ();
studentB.TestQuestion1 ();
studentB.TestQuestion2 ();
studentB.TestQuestion3 ();
Console.Read ();
}
}
}
+结果:
studentA
maybe TestQuestion1 [ ]a.A b.B c.C d.D
answer: b
maybe TestQuestion2 [ ] a.A b.B c.C d.D
answer: c
maybe TestQuestion3 [ ] a.A b.B c.C d.D
answer: a
maybe TestQuestion1 [ ]a.A b.B c.C d.D
answer: c
maybe TestQuestion2 [ ] a.A b.B c.C d.D
answer: b
maybe TestQuestion3 [ ] a.A b.B c.C d.D
answer: a