CSharp设计模式读书笔记(23):模板方法模式(学习难度:★★☆☆☆,使用频率:★★★☆☆)
2024-10-18 14:13:19
模板方法模式:定义一个操作中算法的框架,而将一些步骤延迟到子类中。模板方法模式使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
模式角色与结构:
实现代码:
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..."); //满汉全席
}
}
}
最新文章
- 8bit YUV4:2:2格式对应的颜色
- 基于TCP和多线程实现无线鼠标键盘-InputMethodManager
- php中opendir函数用法实例
- unity安卓和IOS读写目录
- LYDSY模拟赛day3 涂色游戏
- OpenCV图像的二值化
- 在Dreamweaver中安装Emmet(zen-coding)
- 解决Selenium Webdriver执行测试时,每个测试方法都打开一个浏览器窗口的问题
- ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
- uploadify插件实现多个图片上传并预览
- 微软SpeechRecognitionEngine
- 方法输出C++输出斐波那契数列的几种方法
- C#中的逆变和协变
- Spring实战——缓存
- 关于curl / curl_multi的一些实验
- 201521123010 《Java程序设计》第8周学习总结
- CentOS7下安装Docker-Compose
- 设置QPushbutton按钮背景、鼠标滑过状态、鼠标点击后状态用法
- Django--ORM相关操作
- 小程序getLocation出现的各种问题汇总