模板方法模式(template method pattern) 详细解释

本文地址: http://blog.csdn.net/caroline_wendy

模板方法模式(template method pattern): 在一个方法中定义一个算法的骨架, 而将一些步骤延迟到子类中.

模板方法使得子类能够在不改变算法结构的情况下, 又一次定义算法中的某些步骤.

模板方法能够进行挂钩(hook), 钩子(hook)是一种被声明在抽象类中的方法, 但仅仅有空的或者默认的实现.

钩子的存在, 能够让子类有能力对算法的不同点进行挂钩.

抽象类的框架:

/**
* @time 2014年6月18日
*/
package template_method; /**
* @author C.L.Wang
*
*/
public abstract class AbstractClass { final void templateMethod() {
primitiveOperation1();
primitiveOperation2();
concreteOperation();
hook();
} abstract void primitiveOperation1(); abstract void primitiveOperation2(); final void concreteOperation() { } void hook() {}
}

面向对象原则:

好莱坞原则: 别调用我们, 我们会调用你.

详细方法:

1. 抽象类(abstract class), 包括模板方法(template method), 抽象操作(abstract operation),

详细操作(concrete operation), 和钩子(hook).

/**
* @time 2014年6月18日
*/
package template_method; /**
* @author C.L.Wang
*
*/
public abstract class CaffeineBeverage { final void prepareRecipe() { //模板方法
boilWater();
brew();
pourInCup();
if(customerWantsCondiments()) {
addCondiments();
}
} abstract void brew(); //抽象操作 abstract void addCondiments(); void boilWater() { //详细操作
System.out.println("Boiling water");
} void pourInCup() {
System.out.println("Pouring into cup");
} boolean customerWantsCondiments() { //钩子
return true;
} }

2. 详细类(concrete class), 继承(extend) 抽象类(abstract class).

/**
* @time 2014年6月18日
*/
package template_method; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; /**
* @author C.L.Wang
*
*/
public class CoffeeWithHook extends CaffeineBeverage { /* (non-Javadoc)
* @see template_method.CaffeineBeverage#brew()
*/
@Override
void brew() {
// TODO Auto-generated method stub
System.out.println("Dripping Coffee through filter");
} /* (non-Javadoc)
* @see template_method.CaffeineBeverage#addCondiments()
*/
@Override
void addCondiments() {
// TODO Auto-generated method stub
System.out.println("Adding Sugar and Milk");
} public boolean customerWantsCondiments() { //钩子 String answer = getUserInput(); if (answer.toLowerCase().startsWith("y")) {
return true;
} else {
return false;
} } private String getUserInput() { String answer = null; System.out.println("Would you like milk and sugar with your coffee (y/n)? "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try {
answer = in.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your answer");
} if (answer == null) {
return "no";
} return answer;
} } /**
* @time 2014年6月18日
*/
package template_method; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; /**
* @author C.L.Wang
*
*/
public class TeaWithHook extends CaffeineBeverage { /* (non-Javadoc)
* @see template_method.CaffeineBeverage#brew()
*/
@Override
void brew() {
// TODO Auto-generated method stub
System.out.println("Steeping the tea");
} /* (non-Javadoc)
* @see template_method.CaffeineBeverage#addCondiments()
*/
@Override
void addCondiments() {
// TODO Auto-generated method stub
System.out.println("Adding Lemon");
} public boolean customerWantsCondiments() { String answer = getUserInput(); if (answer.toLowerCase().startsWith("y")) {
return true;
} else {
return false;
} } private String getUserInput() { String answer = null; System.out.println("Would you like lemon with your tea (y/n)? "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try {
answer = in.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your answer");
} if (answer == null) {
return "no";
} return answer;
} }

3. 測试类, 包括钩子(hook)操作.

/**
* @time 2014年6月18日
*/
package template_method; /**
* @author C.L.Wang
*
*/
public class BeverageTestDrive { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TeaWithHook teaHook = new TeaWithHook();
CoffeeWithHook coffeeHook = new CoffeeWithHook(); System.out.println("\nMaking tea...");
teaHook.prepareRecipe(); System.out.println("\nMaking coffee...");
coffeeHook.prepareRecipe();
} }

4. 输出:

Making tea...
Boiling water
Steeping the tea
Pouring into cup
Would you like lemon with your tea (y/n)? y
Adding Lemon Making coffee...
Boiling water
Dripping Coffee through filter
Pouring into cup
Would you like milk and sugar with your coffee (y/n)?
n

设计模式 - 模板方法模式(template method pattern) 具体解释的更多相关文章

  1. 设计模式 - 模板方法模式(template method pattern) JFrame 具体解释

    模板方法模式(template method pattern) JFrame 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考模板方法模式(templ ...

  2. 设计模式 - 模板方法模式(template method pattern) 排序(sort) 具体解释

    模板方法模式(template method pattern) 排序(sort) 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考模板方法模式(tem ...

  3. 乐在其中设计模式(C#) - 模板方法模式(Template Method Pattern)

    原文:乐在其中设计模式(C#) - 模板方法模式(Template Method Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 模板方法模式(Template Method ...

  4. 二十四种设计模式:模板方法模式(Template Method Pattern)

    模板方法模式(Template Method Pattern) 介绍定义一个操作中的算法的骨架,而将一些步骤延迟到子类中.Template Method使得子类可以不改变一个算法的结构即可重定义该算法 ...

  5. 模板方法模式(Template Method Pattern)——复杂流程步骤的设计

    模式概述 在现实生活中,很多事情都包含几个实现步骤,例如请客吃饭,无论吃什么,一般都包含点单.吃东西.买单等几个步骤,通常情况下这几个步骤的次序是:点单 --> 吃东西 --> 买单. 在 ...

  6. 设计模式(九): 从醋溜土豆丝和清炒苦瓜中来学习"模板方法模式"(Template Method Pattern)

    今天是五.四青年节,祝大家节日快乐.看着今天这标题就有食欲,夏天到了,醋溜土豆丝和清炒苦瓜适合夏天吃,好吃不上火.这两道菜大部分人都应该吃过,特别是醋溜土豆丝,作为“鲁菜”的代表作之一更是为大众所熟知 ...

  7. java设计模式 模板方法模式Template Method

    设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了可重用代码.让代码更容易被他人理解.保证代码可靠性.毫无疑问,设计模式于己 ...

  8. 模板方法模式(Template Method Pattern)

    模板方法模式是一种基于继承的代码复用技术,定义一个操作中的算法的骨架,而将步骤延迟到子类中.模板方法使得子类可以不改变一个算法的结构即可重定义算法的某些特定步骤. 模式中的角色 抽象类(Abstrac ...

  9. 使用 C# (.NET Core) 实现模板方法模式 (Template Method Pattern)

    本文的概念内容来自深入浅出设计模式一书. 项目需求 有一家咖啡店, 供应咖啡和茶, 它们的工序如下: 咖啡: 茶: 可以看到咖啡和茶的制作工序是差不多的, 都是有4步, 其中有两步它们两个是一样的, ...

随机推荐

  1. bzoj 4769: 超级贞鱼 -- 归并排序

    4769: 超级贞鱼 Time Limit: 1 Sec  Memory Limit: 128 MB Description 马达加斯加贞鱼是一种神奇的双脚贞鱼,它们把自己的智慧写在脚上——每只贞鱼的 ...

  2. bzoj1393 旅游航道

    Description SGOI旅游局在SG-III星团开设了旅游业务,每天有数以万计的地球人来这里观光,包括联合国秘书长,各国总统和SGOI总局局长等.旅游线路四通八达,每天都有总躲得载客太空飞船在 ...

  3. Jeeplus框架中问题解决

    1,文件上传后图片显示的问题 (1)问题:在这个组件的文档介绍里面写了这个组件是有预览功能的,但是我没有找到,就自己写了这个小功能. 在框架中下图中,这个文件上传组件只能将文件上传,然后将文件名显示出 ...

  4. Linux中/proc目录下文件详解(转贴)

      转载:http://www.sudu.cn/info/index.php?op=article&id=302529   Linux中/proc目录下文件详解(一) 声明:可以自由转载本文, ...

  5. Springboot集成Jedis + Redisson(已自测)

    原文:https://blog.csdn.net/c_zyer/article/details/79415728 本文主要跟大家分享在Springboot中集成Jedis和Redisson的方法.为什 ...

  6. ArcGIS for Android图层记录数,图层选择记录,图层字段数

    Log.d("图层记录数:", "" + pFeatureLayer.getFeatureTable().getNumberOfFeatures()); Log ...

  7. ThinkPHP:入门安装 (1)

    1.下载ThinkPHP包 2.引入ThinkPHP.php创建目录文件, 默认ThinkPHP框架所在文档目录 <?php //加载框架入口文件 require './ThinkPHP/Thi ...

  8. 4)linux程序设计入门--时间概念

    )程序设计入门--时间概念 前言:Linux下的时间概念 这一章我们学习Linux的时间表示和计算函数 时间的表示 时间的测量 计时器的使用 .时间表示 在程序当中,我们经常要输出系统当前的时间,比如 ...

  9. linux系统编程:守护进程详解及创建,daemon()使用

    一,守护进程概述 Linux Daemon(守护进程)是运行在后台的一种特殊进程.它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件.它不需要用户输入就能运行而且提供某种服务,不是对整个 ...

  10. 开源 免费 java CMS - FreeCMS1.5-数据对象-info

    下载地址:http://code.google.com/p/freecms/ info 在信息页静态化时,系统会自动向模板文件传递currInfo对象,此对象存储当前信息.在使用信息相关标签时,标签会 ...