模板方法模式(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. cocos2d-android 使用 cocos2d 绘图

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha cocos2d-android-1 https://github.com/ZhouWei ...

  2. finish/onDestroy/System.exit()的区别

    Activity.finish():Call this when your activity is done and should be closed. 在你的activity动作完成的时候,或者Ac ...

  3. 51..分治算法练习:  4378 【Laoguo】循环比赛

    时间限制: 1 s 空间限制: 1000 KB 题目等级 : 黄金 Gold 题解 查看运行结果 题目描述 Description 设有n个选手进行循环比赛,其中n=2的m次方,要求每名选手要与其他n ...

  4. 实用在线小工具 -- JS代码压缩工具

        实用在线小工具 -- JS代码压缩工具 将JS代码进行压缩可以减少内存占用,下面链接是一个在线JS代码压缩工具,它将多余的空格和换行符压缩了. JS代码压缩工具链接:http://jspack ...

  5. IndiaHacks 2016 - Online Edition (Div. 1 + Div. 2) B. Bear and Compressing 暴力

    B. Bear and Compressing 题目连接: http://www.codeforces.com/contest/653/problem/B Description Limak is a ...

  6. C# 时间戳与当前时间互相转换

    时间戳: Unix时间戳(Unix timestamp),或称Unix时间(Unix time).POSIX时间(POSIX time),是一种时间表示方式,定义为从格林威治时间1970年01月01日 ...

  7. Java乱码解决

    简述 乱码是JAVA开发时经常遇到的问题.主要出现在四种情况: 1.         系统接口之间 2.         POST提交数据 3.         GET提交数据和URL路径 4.    ...

  8. undefined详解

    [对于<JS高级程序设计>的理解] “即使未初始化的变量会自动被赋值undefined值,但显式地初始化变量依然是明智的选择.如果能够做到这一点,那么当typeof操作符返回‘undefi ...

  9. java多线程知识汇总(三)如何选择锁?如何加锁

    1.锁,保证的是被锁的代码,一次执行完毕才能被其他线程执行,锁保证了一个线程执行过程中不被其他线程打断.以保证数据的准确性. 2.数据的读写过程,是有冲突的,当一个线程正在读数据,另一个线程正在写同一 ...

  10. Android开发之MdiaPlayer详解

    Android开发之MdiaPlayer详解 MediaPlayer类可用于控制音频/视频文件或流的播放,我曾在<Android开发之基于Service的音乐播放器>一文中介绍过它的使用. ...