设计模式学习之模板方法模式(TemplateMethod,行为型模式)(9)

时间:2023-03-09 00:24:44
设计模式学习之模板方法模式(TemplateMethod,行为型模式)(9)

设计模式学习之模板方法模式(TemplateMethod,行为型模式)(9)

一、什么是模板方法模式

Template Method模式也叫模板方法模式,是行为模式之一,它把具有特定步骤算法中的某些必要的处理委让给抽象方法,通过子类继承对抽象方法的不同实现改变整个算法的行为。

二、模板方法模式的应用场景

Template Method模式一般应用在具有以下条件的应用中:

- 具有统一的操作步骤或操作过程

- 具有不同的操作细节

- 存在多个具有同样操作步骤的应用场景,但某些具体的操作细节却各不相同

 private static void Main(string[] args)
{ MakeCar bus = new MakeBus();
bus.Make();
MakeCar jeep = new MakeJeep();
jeep.Make();
Console.ReadLine();
} public abstract class MakeCar
{
/// <summary>
/// 组装车头
/// </summary>
public abstract void MakeHead(); /// <summary>
/// 组装车身
/// </summary>
public abstract void MakeBody(); /// <summary>
/// 组装车尾
/// </summary>
public abstract void MakeFoot(); /// <summary>
/// 模板方法
/// </summary>
public void Make()
{
MakeHead();
MakeBody();
MakeFoot();
}
} public class MakeBus : MakeCar
{
public override void MakeHead()
{
Console.WriteLine("组装bus车头");
} public override void MakeBody()
{
Console.WriteLine("组装bus车身");
} public override void MakeFoot()
{
Console.WriteLine("组装bus车尾");
}
}
public class MakeJeep : MakeCar
{
public override void MakeHead()
{
Console.WriteLine("组装jeep车头");
} public override void MakeBody()
{
Console.WriteLine("组装jeep车身");
} public override void MakeFoot()
{
Console.WriteLine("组装jeep车尾");
}
}

.NET 中的Template Method模式

.NET Framework中Template Method模式的使用可以说是无处不在,比如说我们需要自定义一个文本控件,会让它继承于RichTextBox,并重写其中部分事件,如下例所示:

public class MyRichTextBox : RichTextBox

{

    private static bool m_bPaint = true;

    private string m_strLine = "";

    private int m_nContentLength = ;

    private int m_nLineLength = ;

    private int m_nLineStart = ;

    private int m_nLineEnd = ;

    private string m_strKeywords = "";

    private int m_nCurSelection = ;

    protected override void OnSelectionChanged(EventArgs e)

    {
m_nContentLength = this.TextLength; int nCurrentSelectionStart = SelectionStart; int nCurrentSelectionLength = SelectionLength; m_bPaint = false; m_nLineStart = nCurrentSelectionStart; while ((m_nLineStart > ) && (Text[m_nLineStart - ] != ',')&& (Text[m_nLineStart - ] != '{')&& (Text[m_nLineStart - ] != '(')) m_nLineStart--; m_nLineEnd = nCurrentSelectionStart; while ((m_nLineEnd < Text.Length) && (Text[m_nLineEnd] != ',')&& (Text[m_nLineEnd] != '}')&& (Text[m_nLineEnd] != ')')&& (Text[m_nLineEnd] != '{')) m_nLineEnd++; m_nLineLength = m_nLineEnd - m_nLineStart; m_strLine = Text.Substring(m_nLineStart, m_nLineLength); this.SelectionStart = m_nLineStart; this.SelectionLength = m_nLineLength; m_bPaint = true; } protected override void OnTextChanged(EventArgs e) {
// 重写OnTextChanged
}
}

其中OnSelectionChanged()和OnTextChanged()便是Template Method模式中的基本方法之一,也就是子步骤方法,它们的调用已经在RichTextBox中实现了。

参考:http://terrylee.cnblogs.com/archive/2006/07/04/DesignPattern_TemplateMethod.html