前言
在抽象类中封装算法的结构,具体的实现步骤由子类定义,从而达到不改变算法结构的,允许子类重定义方法内容。
代码
public abstract class Teamplate
{
public void TeamplateMethod()
{
Step1();
Step2();
Step3();
}
protected abstract void Step1();
protected abstract void Step2();
protected abstract void Step3();
}
public class ConcreteTemplate : Teamplate
{
protected override void Step1()
{
Console.WriteLine("Step1");
}
protected override void Step2()
{
Console.WriteLine("Step2");
}
protected override void Step3()
{
Console.WriteLine("Step3");
}
}
internal class Program
{
static void Main(string[] args)
{
Teamplate teamplate = new ConcreteTemplate();
teamplate.TeamplateMethod();
Console.ReadLine();
}
}
运行结果