设计模式(21)模板模式
模式介绍
模板模式定义了操作的轮廓或骨架,由子类定义的具体步骤。
示例
我们以制作面包为例,通常会分为三步:和面、烤、切。
抽象的制作面包方法:
/// <summary>
/// The AbstractClass participant which contains the template method.
/// </summary>
abstract class Bread
{
public abstract void MixIngredients();
public abstract void Bake();
public virtual void Slice()
{
Console.WriteLine("Slicing the " + GetType().Name + " bread!");
}
// The template method
public void Make()
{
MixIngredients();
Bake();
Slice();
}
}
具体的多种制作面包方法:
class TwelveGrain : Bread
{
public override void MixIngredients()
{
Console.WriteLine("Gathering Ingredients for 12-Grain Bread.");
}
public override void Bake()
{
Console.WriteLine("Baking the 12-Grain Bread. (25 minutes)");
}
}
class Sourdough : Bread
{
public override void MixIngredients()
{
Console.WriteLine("Gathering Ingredients for Sourdough Bread.");
}
public override void Bake()
{
Console.WriteLine("Baking the Sourdough Bread. (20 minutes)");
}
}
class WholeWheat : Bread
{
public override void MixIngredients()
{
Console.WriteLine("Gathering Ingredients for Whole Wheat Bread.");
}
public override void Bake()
{
Console.WriteLine("Baking the Whole Wheat Bread. (15 minutes)");
}
}
客户端调用:
static void Main(string[] args)
{
Sourdough sourdough = new Sourdough();
sourdough.Make();
TwelveGrain twelveGrain = new TwelveGrain();
twelveGrain.Make();
WholeWheat wholeWheat = new WholeWheat();
wholeWheat.Make();
Console.ReadKey();
}
总结
模板模式允许对象建立算法的框架,但是将实现细节留给要实现的具体类。
源代码
https://github.com/exceptionnotfound/DesignPatterns/tree/master/TemplateMethod
原文
https://www.exceptionnotfound.net/the-daily-design-pattern-template-method/