《C#设计模式》==>模板方法模式

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

namespace DesignPattern1
{
    internal class TemplateMethodPattern
    {
    }
    //
    //模板方法模式:是一种类行为型模式。定义一个操作中算法的框架,而将一些步骤延迟到子类中,模板方法模式使得子类不改变一个算法的结构即可重定义改算法的某些特定步骤

    /*
    抽象类
    具体子类
     */

    abstract class Account
    {

        //基本放大--具体方法
        public bool Validate(string account, string password)
        {
            Console.WriteLine("账号:{0}", account);
            Console.WriteLine("密码:{0}", password);
            if (account.Equals("张无忌") && password.Equals("123456"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        //基本方法--抽象方法
        public abstract void CalculateInterest();

        //基本方法--具体方法
        public void Display()
        {
            Console.WriteLine("显示利息");
        }

        //模板方法
        public void Handle(string account, string password)
        {
            if (!Validate(account, password))
            {
                Console.WriteLine("账户或密码错误!");
                return;
            }
            CalculateInterest();
            Display();
        }
    }

    //活期账户类  充当具体子类
    class CurrentAccount : Account
    {
        //覆盖父类的抽象基本方法
        public override void CalculateInterest()
        {
            Console.WriteLine("按活期利率计算利息。");
        }
    }
    class SavingAccount : Account
    {
        //覆盖父类的抽象基本方法
        public override void CalculateInterest()
        {
            Console.WriteLine("按定期利率计算利息。");
        }
    }
    //客户端测试
    class program
    {
        public void main() {
            //可以将具体子类的名字存储在配置文件中  然后在程序中通过反射进行创建  实现设计的开闭原则
            //此处省略  直接创建
            Account account = new SavingAccount();
            account.Handle("张无忌","123456");

            account = new CurrentAccount();
            account.Handle("赵敏","123456");

            //输出结果
            //账号:张无忌
            //密码:123456
            //按定期利率计算利息
            //显示利息

            //账号:赵敏
            //密码:123456
            //按活期利率计算利息
            //显示利息


        }
    }


}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值