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

模式角色与结构:

实现代码:

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

最新文章

  1. 8bit YUV4:2:2格式对应的颜色
  2. 基于TCP和多线程实现无线鼠标键盘-InputMethodManager
  3. php中opendir函数用法实例
  4. unity安卓和IOS读写目录
  5. LYDSY模拟赛day3 涂色游戏
  6. OpenCV图像的二值化
  7. 在Dreamweaver中安装Emmet(zen-coding)
  8. 解决Selenium Webdriver执行测试时,每个测试方法都打开一个浏览器窗口的问题
  9. ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
  10. uploadify插件实现多个图片上传并预览
  11. 微软SpeechRecognitionEngine
  12. 方法输出C++输出斐波那契数列的几种方法
  13. C#中的逆变和协变
  14. Spring实战——缓存
  15. 关于curl / curl_multi的一些实验
  16. 201521123010 《Java程序设计》第8周学习总结
  17. CentOS7下安装Docker-Compose
  18. 设置QPushbutton按钮背景、鼠标滑过状态、鼠标点击后状态用法
  19. Django--ORM相关操作
  20. 小程序getLocation出现的各种问题汇总

热门文章

  1. jwt (JSON Web Token)官方说明
  2. 惠普4431s 笔记本配置
  3. 用DOS命令获取文件列表
  4. iOS经常使用类别
  5. 【原创】构建高性能ASP.NET站点之二 优化HTTP请求(前端)
  6. UVA - 10714 Ants
  7. POJ1251 Jungle Roads 【最小生成树Prim】
  8. EEPlat的元数据驱动的运行引擎
  9. POJ--1679--The Unique MST【推断MST是否唯一】
  10. Coco2d-x android win7 Python 游戏开发环境的搭建