zoukankan      html  css  js  c++  java
  • 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..."); //满汉全席
            }
        }
    }
  • 相关阅读:
    7.Ubuntu16.04安装Jenkins
    5.在Gitlab创建一个基于Sping Boot Maven项目
    4.ubuntu 16.04.6 离线安装 Git
    CNN注意事项_七月算法5月深度学习班第5次课程笔记
    Github 文件选择性上传
    一个Velocity Template Language学习的框架
    设计模式学习之代理模式(Proxy)
    ibatis入门教程一
    SimpleDataFormat详解
    使用Qmake在树莓派上开发Opencv程序
  • 原文地址:https://www.cnblogs.com/thlzhf/p/3993804.html
Copyright © 2011-2022 走看看