一、

1.The Template Method defines the steps of an algorithm and allows subclasses to provide the implementation for one or more steps.

2.The Template Method Pattern defi nes the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

3.With a hook, I can override the method, or not. It’s my choice.If I don’t, the abstract class provides a default implementation.

4.

二、

1.

 package headfirst.designpatterns.templatemethod.barista;

 public abstract class CaffeineBeverage {

     final void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
} abstract void brew(); abstract void addCondiments(); void boilWater() {
System.out.println("Boiling water");
} void pourInCup() {
System.out.println("Pouring into cup");
}
}

2.

 package headfirst.designpatterns.templatemethod.barista;

 public abstract class CaffeineBeverageWithHook {

     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;
}
}

3.

 package headfirst.designpatterns.templatemethod.barista;

 public class Coffee extends CaffeineBeverage {
public void brew() {
System.out.println("Dripping Coffee through filter");
}
public void addCondiments() {
System.out.println("Adding Sugar and Milk");
}
}

4.

 package headfirst.designpatterns.templatemethod.barista;

 import java.io.*;

 public class CoffeeWithHook extends CaffeineBeverageWithHook {

     public void brew() {
System.out.println("Dripping Coffee through filter");
} public void addCondiments() {
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.print("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.err.println("IO error trying to read your answer");
}
if (answer == null) {
return "no";
}
return answer;
}
}

5.

 package headfirst.designpatterns.templatemethod.barista;

 public class Tea extends CaffeineBeverage {
public void brew() {
System.out.println("Steeping the tea");
}
public void addCondiments() {
System.out.println("Adding Lemon");
}
}

6.

 package headfirst.designpatterns.templatemethod.barista;

 import java.io.*;

 public class TeaWithHook extends CaffeineBeverageWithHook {

     public void brew() {
System.out.println("Steeping the tea");
} public void addCondiments() {
System.out.println("Adding Lemon");
} public boolean customerWantsCondiments() { String answer = getUserInput(); if (answer.toLowerCase().startsWith("y")) {
return true;
} else {
return false;
}
} private String getUserInput() {
// get the user's response
String answer = null; System.out.print("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.err.println("IO error trying to read your answer");
}
if (answer == null) {
return "no";
}
return answer;
}
}

7.

 package headfirst.designpatterns.templatemethod.barista;

 public class BeverageTestDrive {
public static void main(String[] args) { Tea tea = new Tea();
Coffee coffee = new Coffee(); System.out.println("\nMaking tea...");
tea.prepareRecipe(); System.out.println("\nMaking coffee...");
coffee.prepareRecipe(); TeaWithHook teaHook = new TeaWithHook();
CoffeeWithHook coffeeHook = new CoffeeWithHook(); System.out.println("\nMaking tea...");
teaHook.prepareRecipe(); System.out.println("\nMaking coffee...");
coffeeHook.prepareRecipe();
}
}

8.

三、The Hollywood Principle and Template Method

1.The Hollywood Principle Don’t call us, we’ll call you.

2.

3.

4.

5.

四、Sorting with Template Method

1.

 package headfirst.designpatterns.templatemethod.sort;

 public class Duck implements Comparable<Duck> {
String name;
int weight; public Duck(String name, int weight) {
this.name = name;
this.weight = weight;
} public String toString() {
return name + " weighs " + weight;
} public int compareTo(Duck object) { Duck otherDuck = object; if (this.weight < otherDuck.weight) {
return -1;
} else if (this.weight == otherDuck.weight) {
return 0;
} else { // this.weight > otherDuck.weight
return 1;
}
}
}

五、JFrame中的templateMethod的hook方法

1.If you haven’t encountered JFrame, it’s the most basic Swing container and inherits

a paint() method. By default, paint() does nothing because it’s a hook! By overriding
paint(), you can insert yourself into JFrame’s algorithm for displaying its area of the
screen and have your own graphic output incorporated into the JFrame. Here’s
an embarrassingly simple example of using a JFrame to override the paint() hook
method:

2.

 package headfirst.designpatterns.templatemethod.frame;

 import java.awt.*;
import javax.swing.*; public class MyFrame extends JFrame {
private static final long serialVersionUID = 2L; public MyFrame(String title) {
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(300,300);
this.setVisible(true);
} // JFrame’s update algorithm calls paint(). By
// default, paint() does nothing... it’s a hook.
// We’re overriding paint(), and telling the
// JFrame to draw a message in the window.
public void paint(Graphics graphics) {
super.paint(graphics);
String msg = "I rule!!";
graphics.drawString(msg, 100, 100);
} public static void main(String[] args) {
MyFrame myFrame = new MyFrame("Head First Design Patterns");
}
}

六、Applet的hook方法

1.Concrete applets make extensive use of hooks to supply their
own behaviors. Because these methods are implemented as
hooks, the applet isn’t required to implement them.

2.

 package headfirst.designpatterns.templatemethod.applet;

 import java.applet.Applet;
import java.awt.Graphics; public class MyApplet extends Applet {
private static final long serialVersionUID = 2L;
String message; public void init() {
message = "Hello World, I'm alive!";
repaint();
} public void start() {
message = "Now I'm starting up...";
repaint();
} public void stop() {
message = "Oh, now I'm being stopped...";
repaint();
} public void destroy() {
message = "Goodbye, cruel world";
repaint();
} public void paint(Graphics g) {
g.drawString(message, 5, 15);
}
}

3.

七、

1.

Q: When I’m creating a template method, how do I know when to use abstract methods and when to use hooks?
A: Use abstract methods when your subclass MUST provide an implementation of the method or step in the algorithm.
Use hooks when that part of the algorithm is optional. With hooks, a subclass may choose to implement that hook, but it doesn’t have to.

2.

Q: This implementation of sorting
actually seems more like the Strategy
Pattern than the Template Method
Pattern. Why do we consider it
Template Method?
A: You’re probably thinking that
because the Strategy Pattern uses object
composition. You’re right in a way – we’re

using the Arrays object to sort our array, so
that’s similar to Strategy. But remember,
in Strategy, the class that you compose
with implements the entire algorithm. The
algorithm that Arrays implements for sort
is incomplete; it needs a class to fill in the
missing compareTo() method. So, in that
way, it’s more like Template Method.

3.

Q: Are there other examples of
template methods in the Java API?
A: Yes, you’ll find them in a few
places. For example, java.io has a read()
method in InputStream that subclasses
must implement and is used by the tempate
method read(byte b[], int off, int len).

4.

The Strategy and Template Method Patterns both encapsulate algorithms, one by inheritance and one by composition.

HeadFirst设计模式之模板方法模式的更多相关文章

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

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

  2. 折腾Java设计模式之模板方法模式

    博客原文地址:折腾Java设计模式之模板方法模式 模板方法模式 Define the skeleton of an algorithm in an operation, deferring some ...

  3. js设计模式——6.模板方法模式与职责链模式

    js设计模式——6.模板方法模式与职责链模式 职责链模式

  4. [C++设计模式]template 模板方法模式

    模板法模式:定义一个操作中的算法骨架.而将一些步骤延迟到子类中. 依照<headfirst 设计模式>的样例.煮茶和煮咖啡的算法框架(流程)是一样的.仅仅是有些算法的实现是不一样的,有些是 ...

  5. java设计模式之模板方法模式

    模板方法模式 定义一个操作中的算法的骨架,而将一些步骤延迟到子类中. 模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤.通俗的说的就是有很多相同的步骤的,在某一些地方可能有一些差 ...

  6. C#设计模式(14)——模板方法模式(Template Method)

    一.引言 提到模板,大家肯定不免想到生活中的“简历模板”.“论文模板”.“Word中模版文件”等,在现实生活中,模板的概念就是——有一个规定的格式,然后每个人都可以根据自己的需求或情况去更新它,例如简 ...

  7. 【GOF23设计模式】模板方法模式

    来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_模板方法模式.钩子函数.方法回调.好莱坞原则 package com.test.templateMethod; publi ...

  8. [设计模式] 22 模板方法模式 template

    转http://www.jellythink.com/archives/407 在GOF的<设计模式:可复用面向对象软件的基础>一书中对模板方法模式是这样说的:定义一个操作中的算法骨架,而 ...

  9. java_设计模式_模板方法模式_Template Method Pattern(2016-08-11)

    定义: 定义一个操作中算法的骨架,而将一些步骤延迟到子类中,使得子类可以不改变算法的结构即可重定义该算法中的某些特定步骤.这里的算法的结构,可以理解为你根据需求设计出来的业务流程.特定的步骤就是指那些 ...

随机推荐

  1. JavaScript最佳实践:可维护性

    代码约定 一.可读性 代码缩进 包含注释 二.变量和函数命名 变量名应为名词如car或person 函数名应该以动词开始,如getName().返回布尔类型值的函数一般以is开头,如isEnable( ...

  2. [Bootstrap]概述

    ——1.html,css,javascript框架                ——2.一般开发响应式布局或者移动优先的项目可以优先考虑 优点 1.css开发版本(可以直接上手)和源码版本(可根据l ...

  3. 老老实实学习WCF[第二篇] 配置wcf

    老老实实学WCF 第二篇 配置WCF 在上一篇中,我们在一个控制台应用程序中编写了一个简单的WCF服务并承载了它.先回顾一下服务端的代码: using System; using System.Col ...

  4. Apache 使用密码文件验证用户

    使用文本文件作为密码文件 创建密码文件 需要使用htpasswd.exe文件来创建用户密码文件 语法: htpasswd -c '文件完整路径' 用户名 向一个用户密码文件中添加一个新用户 语法: h ...

  5. Python快速入门学习笔记(三)——函数的定义与调用

    定义函数 Python中定义函数的格式为: def fun([参数列表]): ... 函数在执行到return语句时结束,并将结果返回.如果没有return语句,函数执行完毕后返回None. 例: d ...

  6. must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int)问题

    依照视屏编写代码如下 class MyButtonListener implements OnClickListener{ @Override public void onClick(View v){ ...

  7. Android基于GridView实现的翻牌游戏效果

    好久没有写博客了,上一篇博文距现在都有三个多月了,实在是惭愧.但是这段时间仍然是在忙于项目或是自我充电.这几天实现了一个基于GridView的翻牌动画效果,这里就将其整理出来同各位分享. 一.整体介绍 ...

  8. SQL存储过程和触发器

    一. 存储过程 1.  有关概念 存储过程是由SQL语句及控制流语句组成的集合.调用一个存储过程,可以一次性地执行过程中的所有语句.从这一点来说,它类似于程序. 存储过程由用户建立,它作为数据库的一个 ...

  9. TimesTen的安装和连接

    注:本文只是单独用TimesTen,和Oracle一起用的不在本文讨论之内.开发语言为C#. TimesTen的过多介绍请访问Oracle官网,不过官网打开够慢的. 1.安装驱动 本人用的是ODP.N ...

  10. MQ 2035(MQRC_NOT_AUTHORIZED)

    当使用MQ7.1或7.5时,如果使用MQ管理员账号去连接MQ服务器,可能会报以下的错误,提示你权限不足. 2035 MQRC_NOT_AUTHORIZED 在之前的版本中是没有这个问题的. 原因是在7 ...