模板方法模式(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. luogu P1965 转圈游戏

    题目描述 n 个小伙伴(编号从 0 到 n-1)围坐一圈玩游戏.按照顺时针方向给 n 个位置编号,从0 到 n-1.最初,第 0 号小伙伴在第 0 号位置,第 1 号小伙伴在第 1 号位置,……,依此 ...

  2. BZOJ1017 魔兽地图DotR (树上背包)

    一道背包的神题,用到了树上dp和背包dp,这个题的特殊性在于儿子对于父亲节点是有影响的,所以用f[i][j][k]表示第i号装备,其中用j个来合成上层装备,花费k元所能获得最大的力量值. 然后对于每一 ...

  3. Codeforces Beta Round #80 (Div. 1 Only) D. Time to Raid Cowavans 分块

    D. Turtles Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/103/problem/D ...

  4. Read UNIQUE ID and flash size method for stm32

    /* 读取stm32的unique id 与 flash size */ /* func: unsigned int Read_UniqueID_Byte(unsigned char offset) ...

  5. Control an LM317T with a PWM signal

    http://www.edn.com/design/analog/4363990/Control-an-LM317T-with-a-PWM-signal The LM317T from Nationa ...

  6. Android 信息分享实现

    一.短信分享 01Intent intent = new Intent(Intent.ACTION_SEND);02// intent.setType("text/plain"); ...

  7. 机器学习: 神经网络中的Error函数

    利用神经网络做分类的时候,可以将神经网络看成一个mapping function,从输入到输出经过复杂的非线性变换.而输出的预测值与实际的目标值总是存在一定偏差的,一般利用这种偏差建立error 函数 ...

  8. awk排序作业

    输入:给定一个hotelinfo文件,文件格式如下: shanghai_city_7208      上海全季酒店淮海路店 shanghai_city_14744     锦江之星上海金山城市沙滩店 ...

  9. ndk 编译 c++ 兼容性问题汇总整理

    转自:http://blog.csdn.net/wenrenwang/article/details/12003671 1.__int64找不到符号 采用int64_t来代替: #if defined ...

  10. oc 第五天(内存管理)

    OC的重点: 内存管理 1 基本原理     OC的内存回收机制是和JAVA的自动回收机制是不同的,它有两种模式,或者准确的说是同 一种模式的两种不同体现,下面简单总结下. 1手动内存回收       ...