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

时间:2023-03-09 01:33:39
CSharp设计模式读书笔记(23):模板方法模式(学习难度:★★☆☆☆,使用频率:★★★☆☆)

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

模式角色与结构:

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..."); //满汉全席
}
}
}