美文网首页
{C#}设计模式辨析.模板方法

{C#}设计模式辨析.模板方法

作者: 码农猫爸 | 来源:发表于2021-08-03 16:06 被阅读0次

背景

  • 具有相同的结构,仅部分定制时
  • 具有相同的参数类,传参即可生成模板类时
  • 与建造者的异同

示例

using System;
using static System.Console;

namespace DesignPattern_TemplateMethod
{
    public abstract class TemplateMethod
    {
        public void PrintAll()
        {
            PrintFixedHeader();
            PrintContent();
            PrintFooter();

            ReadKey();
        }

        // 固定表头
        private void PrintFixedHeader()
            => WriteLine($"Today is {DateTime.Now}");

        // 正文,必须重写
        protected abstract void PrintContent();

        // 页尾,可选重写
        protected virtual void PrintFooter()
            => WriteLine("This is footer.");
    }

    public class DailyReportTemplate : TemplateMethod
    {
        protected override void PrintContent()
            => WriteLine($"This is daily report content.");
    }

    public class MonthlyReportTemplate : TemplateMethod
    {
        protected override void PrintContent()
            => WriteLine($"This is monthly report content.");

        protected override void PrintFooter()
            => WriteLine("This is special footer.");
    }

    public class Client
    {
        private readonly TemplateMethod template;

        public Client(TemplateMethod template)
        {
            this.template = template;
        }

        public void Print() => template.PrintAll();
    }

    class Demo
    {
        static void Main(string[] args)
        {
            // 增加年报时,应
            // - 增加Builder的年报子类,不影响旧代码
            // - 更换为年报实例,影响本类代码,必须
            var template = new DailyReportTemplate();
            var client = new Client(template);
            client.Print();
        }
    }
}

相关文章

网友评论

      本文标题:{C#}设计模式辨析.模板方法

      本文链接:https://www.haomeiwen.com/subject/fnuuvltx.html