模板方法模式(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. 51nod1203 JZPLCM 线段树 + 扫描线

    不算很难的一道题 原题的数据虽然很小,但是我们不能欺负它,我们就要当$S[i] \leqslant 10^9$来做这题 最小公倍数 = 所有的质因数取可能的最大幂相乘 对于$> \sqrt S$ ...

  2. BZOJ1002: [FJOI2007]轮状病毒 (DP)

    标准做法似乎应该是计算生成树数量的基尔霍夫矩阵之类的.. 我看到的做法是一个神奇的高精度dp,当然以后这个blahblahblah矩阵还是要搞一下..   参考(抄袭)网址   这个dp的原理就是把环 ...

  3. 【lct】poj2763 Housewife Wind

    题意:给你一棵树,边带权,支持两种操作:修改某条边的权值:查询两点之间的最短路. lct主要实现单点修改和路径和. 修改x结点的值只需将x Splay到其所在辅助树的根,然后修改其值,再maintai ...

  4. Flask请求上下文源码讲解,简单的群聊单聊web

    请求上下文流程图 群聊html代码 <!DOCTYPE html> <html lang="en"> <head> <meta chars ...

  5. poj 1703 并查集

    题意:在这个城市里有两个黑帮团伙,现在给出N个人,问任意两个人他们是否在同一个团伙 输入D x y代表x于y不在一个团伙里 输入A x y要输出x与y是否在同一团伙或者不确定他们在同一个团伙里 链接: ...

  6. Java并发(七):双重检验锁定DCL

    双重检查锁定(Double Check Lock,DCL) 1.懒汉式单例模式,无法保证线程安全: public class Singleton { private static Singleton ...

  7. HDU 4183

    给出一个有向图,以及src和dst.判断是否存在从src到dst的两条路径,使得除了src和dst外,没有其它点同时属于两条路径. 给每个点一个为1的点容量(src和dst为2),边的容量也是1,然后 ...

  8. 使用Keras实现机器翻译(英语—>法语)

    import numpy as np from keras.models import Model from keras.models import load_model from keras.lay ...

  9. 更新teaching中fdSubjectID为null的老数据

    UPDATE wkwke.tbTeachingV3 teaching SET teaching.fdSubjectID = (                    SELECT fdValue FR ...

  10. [置顶] getopt_long函数基本用法-linux

    一.感性认识: [c-sharp]  view plain copy   #include <stdio.h> #include <getopt.h> char * l_opt ...