模板方法模式:模板方法模式准备一个抽象类,将部分逻辑以具体方法以及具体构造子的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现。先制定一个顶级逻辑框架,而将逻辑的细节留给具体的子类去实现。
参看下列简单实例代码:
AbstractClass为基类,包含模板方法TemplateMethod(),在这个方法中调用PrimitiveOperation1()和PrimitiveOperation2(),其中这两个方法由子类ConcreteClass实现.
using System;
// "AbstractClass"
abstract class AbstractClass
{
// Methods
abstract public void PrimitiveOperation1();
abstract public void PrimitiveOperation2();
// The Template method
public void TemplateMethod()
{
Console.WriteLine(
"In AbstractClass.TemplateMethod()");
PrimitiveOperation1();
PrimitiveOperation2();
}
}
// "ConcreteClass"
class ConcreteClass : AbstractClass
{
// Methods
public override void PrimitiveOperation1()
{
Console.WriteLine(
"Called ConcreteClass.PrimitiveOperation1()");
}
public override void PrimitiveOperation2()
{
Console.WriteLine(
"Called ConcreteClass.PrimitiveOperation2()");
}
}
/// <summary>
/// Client test
/// </summary>
public class Client
{
public static void Main( string[] args )
{
// Create instance and call template method
ConcreteClass c = new ConcreteClass();
c.TemplateMethod();
}
}
|
Output
In AbstractClass.TemplateMethod()
Called ConcreteClass.PrimitiveOperation1()
Called ConcreteClass.PrimitiveOperation2()
|
|