• CSharp设计模式读书笔记(23):模板方法模式(学习难度:★★☆☆☆,使用频率:★★★☆☆)


    模板方法模式:定义一个操作中算法的框架,而将一些步骤延迟到子类中。模板方法模式使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

    模式角色与结构:

     

    实现代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace CSharp.DesignPattern.TemplateMethodPattern
    {
        class Program
        {
            static void Main(string[] args)
            {
                Account account = new CurrentAccount(); // 还可以通过配置文件和反射来决定创建哪个子类
                account.Handle("", "");
            }
        }
    
        abstract class Account
        {
            //基本方法——具体方法 
            public bool Validate(string account, string password)
            {
                if (account.Equals("") && password.Equals(""))
                {
                    return true;
                }
                return false;
            }
    
            //基本方法——抽象方法 
            public abstract void CalculateInterest();
    
            //基本方法——具体方法 
            public void Display()
            { }
    
            //基本方法——钩子方法(子类控制父类)
            public virtual bool IsLeader()
            {
                return true;
            }
    
            // 模板方法
            public void Handle(string account, string password)
            {
                if (!Validate(account, password))
                {
                    return;
                }
    
                if (IsLeader())
                {
                    CalculateInterest();
                }
    
                Display();
            }
        }
    
        class CurrentAccount : Account
        {
            // 覆盖父类的抽象基本方法 
            public void CalculateInterest()
            {
                Console.WriteLine("Current Account..."); //吃面条
            }
        }
    
        class SavingAccount : Account
        {
            // 覆盖父类的抽象基本方法 
            public void CalculateInterest()
            {
                Console.WriteLine("Saving Account..."); //满汉全席
            }
        }
    }
  • 相关阅读:
    牛客练习赛83题解
    1525 F. Goblins And Gnomes (最小顶点覆盖输出方案)
    hash表
    欧拉回路输出方案
    dp优化
    1
    fwt原理学习和一些拓展
    SpringBoot在IDEA中的配置
    ES: memory locking requested for elasticsearch process but memory is not locked
    Prometheus监控大数据
  • 原文地址:https://www.cnblogs.com/thlzhf/p/3993804.html
Copyright © 2020-2023  润新知