设计模式学习总结11 行为型6 TemplateMethod模版方法模式

TemplateMethod模版方法模式(行为型)

作用

模版方法使算法的具体步骤推迟到子类实现。算法的结构稳定,但是算法内部细分的操作可以在其他地方实现。

Role
The  Template  Method  pattern  enables  algorithms  to  defer  certain  steps  to  subclasses. The structure of the algorithm does not change, but small well-defined parts of its operation are handled elsewhere.

设计

Algorithm,含有模版方法的类
TemplateMethod,模版方法,将其内部的操作退到其他类去实现
IPrimitives,模版方法推到其他类的操作接口
AnyClass,实现了IPrimitives接口的类
Operation,模版方法需要完成操作的一个子方法

举例

Algorithm,日志管理器
TemplateMethod,记录日志
IPrimitives,记录日志的操作步骤规范1、获取日志信息;2、拆分信息到各字段;3、将各字段信息存入相应记录媒体
AnyClass,各种实现了日志记录步骤的方法
Operation,记录日志的操作步骤

实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Templatemethod
{
       
interface IPrimitives {
         
string Operation1();
         
string Operation2();
       }

       
class Algorithm {
         
public void TemplateMethod(IPrimitives a) {
           
string s =
             a.Operation1() 
+
             a.Operation2();
             Console.WriteLine(s);
         }
       }

       
class ClassA : IPrimitives {
         
public string Operation1() {
           
return "ClassA:Op1 ";
         }
         
public string Operation2() {
           
return "ClassA:Op2 ";
         }
       }

       
class ClassB : IPrimitives {
         
public string Operation1() {
           
return "ClassB:Op1 ";
         }
         
public string Operation2() {
           
return "ClassB.Op2 ";
         }
       }
    
    
class Program
    {
        
static void Main(string[] args)
        {
           Algorithm m 
= new Algorithm();

           m.TemplateMethod(
new ClassA());
           m.TemplateMethod(
new ClassB());
           Console.ReadLine();
        }
    }
}

应用场景

当一个算法可以分解出共同的行为模式;

根据每个子类的类型变化操作行为
Use the Template Method pattern when…
•  Common behavior can be factored out of an algorithm.
•  The behavior varies according to the type of a subclass.

总结

Template Method模板方法模式是一种行为型模式。解决某个有稳定的操作结构,但各个子步骤却有很多改变的需求,或者由于固有的原因而无法和任务的整体结构同时实现。 GoF《设计模式》中说道:定义一个操作中的算法的步骤,将一些步骤延迟到子类中实现。Template Method使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

原文地址:https://www.cnblogs.com/utopia/p/1681066.html