设计模式(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/

转载于:https://www.cnblogs.com/talentzemin/p/9967673.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值