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
//按活期利率计算利息
//显示利息
}
}
}