1、 概念
定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类不改变算法的结构也可以重定义某些算法的特定步骤。
2、 模型
模板方法模式在编程中是经常用到的,就不做详细解释了。常见模型如下:
using System; using System.Collections.Generic; using System.Text; namespace TemplateMethod { public abstract class TemplateSuper//父类定义了算法框架 { public void InitialOperation() { Console.WriteLine("父类的具体算法。"); } public abstract void AbstractMethod(); } public class CreateTemplate1:TemplateSuper//继承父类并实现部分算法1 { public override void AbstractMethod() { Console.WriteLine("子类实现部分算法1"); } } public class CreateTemplate2 : TemplateSuper//继承父类并实现部分算法2 { public override void AbstractMethod() { Console.WriteLine("子类实现部分算法2"); } } } 客户端: using System; using System.Collections.Generic; using System.Text; namespace TemplateMethod { class Program { static void Main(string[] args) { TemplateSuper tsuper; tsuper = new CreateTemplate1(); tsuper.InitialOperation(); tsuper.AbstractMethod(); tsuper = new CreateTemplate2(); tsuper.AbstractMethod(); Console.ReadLine(); } } }
结果:
那么可以发现,模板方法模式和前面的策略模式很像,都是继承父类实现不同的算法。但是它们是有区别的,从定义可以看到,模板方法模式:一个操作中的算法的骨架,而将一些步骤延迟到子类中。策略模式:定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响使用算法的客户。
它们的区别是,模板方法模式,父类中已经有了算法的骨架,只是延迟了一些步骤到子类中处理,也就是说,子类只实现了一部分算法。而策略模式,只是定义了算法家族,子类完全去实现了,不同的子类实现的算法完全不同。也就是整体都由子类完成,算法也改变了。模板方法模式是部分实现,策略模式是整体实现,这就是它们的区别。