Template Method is a behavioral design pattern and it’s used to create a method stub and deferring some of the steps of implementation to the subclasses.Template method defines the steps to execute an algorithm and it can provide default implementation that might be common for all or some of the subclasses.
Let’s understand this pattern with an example, suppose we want to provide an algorithm to build a house. The steps need to be performed to build a house are – building foundation, building pillars, building walls and windows. The important point is that the we can’t change the order of execution because we can’t build windows before building the foundation. So in this case we can create a template method that will use different methods to build the house.
Now building the foundation for a house is same for all type of houses, whether its a wooden house or a glass house. So we can provide base implementation for this, if subclasses want to override this method, they can but mostly it’s common for all the types of houses.
To make sure that subclasses don’t override the template method, we should make it final.
Template Method Abstract Class
Since we want some of the methods to be implemented by subclasses, we have to make our base class as abstract class.
HouseTemplate.java
01 |
package com.journaldev.design.template; |
03 |
public abstract class HouseTemplate { |
05 |
//template method, final so subclasses can't override |
06 |
public final void buildHouse(){ |
11 |
System.out.println("House is built."); |
14 |
//default implementation |
15 |
private void buildWindows() { |
16 |
System.out.println("Building Glass Windows"); |
19 |
//methods to be implemented by subclasses |
20 |
public abstract void buildWalls(); |
21 |
public abstract void buildPillars(); |
23 |
private void buildFoundation() { |
24 |
System.out.println("Building foundation with cement,iron rods and sand"); |
buildHouse() is the template method and defines the order of execution for performing several steps.
Template Method Concrete Classes
We can have different type of houses, such as Wooden House and Glass House.
WoodenHouse.java
01 |
package com.journaldev.design.template; |
03 |
public class WoodenHouse extends HouseTemplate { |
06 |
public void buildWalls() { |
07 |
System.out.println("Building Wooden Walls"); |
11 |
public void buildPillars() { |
12 |
System.out.println("Building Pillars with Wood coating"); |
We could have overridden other methods also, but for simplicity I am not doing that.
GlassHouse.java
01 |
package com.journaldev.design.template; |
03 |
public class GlassHouse extends HouseTemplate { |
06 |
public void buildWalls() { |
07 |
System.out.println("Building Glass Walls"); |
11 |
public void buildPillars() { |
12 |
System.out.println("Building Pillars with glass coating"); |
Template Method Pattern Client
Let’s test our template method pattern example with a test program.
HousingClient.java
01 |
package com.journaldev.design.template; |
03 |
public class HousingClient { |
05 |
public static void main(String[] args) { |
07 |
HouseTemplate houseType = new WoodenHouse(); |
09 |
//using template method |
10 |
houseType.buildHouse(); |
11 |
System.out.println("************"); |
13 |
houseType = new GlassHouse(); |
15 |
houseType.buildHouse(); |
Notice that client is invoking the template method of base class and depending of implementation of different steps, it’s using some of the methods from base class and some of them from subclass.
Output of the above program is:
01 |
Building foundation with cement,iron rods and sand |
02 |
Building Pillars with Wood coating |
04 |
Building Glass Windows |
07 |
Building foundation with cement,iron rods and sand |
08 |
Building Pillars with glass coating |
10 |
Building Glass Windows |
Template Method Class Diagram

Template Method Pattern in JDK
- All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer.
- All non-abstract methods of java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap.
Important Points
- Template method should consists of certain steps whose order is fixed and for some of the methods, implementation differs from base class to subclass. Template method should be final.
- Most of the times, subclasses calls methods from super class but in template pattern, superclass template method calls methods from subclasses, this is known as Hollywood Principle – “don’t call us, we’ll call you.”.
- Methods in base class with default implementation are referred as Hooks and they are intended to be overridden by subclasses, if you want some of the methods to be not overridden, you can make them final, for example in our case we can make buildFoundation() method final because if we don’t want subclasses to override it.
Thats all for template method pattern implementation in java, I hope you liked it.
- 设计模式-模板方法设计模式--Template Method design pattern
/** * Abstract implementation of the {@link org.springframework.context.ApplicationContext} * interf ...
- 设计模式之 - 工厂方法模式 (Factory Method design pattern)
1. 模式意图: 定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类. 2. 别名(Virtual Constructor) 3. 结构 4. 工厂方法模式C ...
- Chain Of Responsibility Design Pattern Example
Avoid coupling the sender of a request to the receiver by giving more than one object a chance to ha ...
- Design Pattern - Service Locator Pattern--转载
原文地址:http://www.tutorialspoint.com/design_pattern/service_locator_pattern.htm The service locator de ...
- Design Pattern —— Prototype /Template Method/Iterator/Composite/Bridge
Prototype /Template Method/Iterator/Composite/Bridge 为什么把这五种设计模式放一起呢,没什么太高大上的原因,就是因为这五种模式JAVA开发最基本的特 ...
- 设计模式 - 模板方法模式(template method pattern) JFrame 具体解释
模板方法模式(template method pattern) JFrame 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考模板方法模式(templ ...
- java设计模式大全 Design pattern samples in Java(最经典最全的资料)
java设计模式大全 Design pattern samples in Java(最经典最全的资料) 2015年06月19日 13:10:58 阅读数:11100 Design pattern sa ...
- java设计模式 模板方法模式Template Method
设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了可重用代码.让代码更容易被他人理解.保证代码可靠性.毫无疑问,设计模式于己 ...
- 深入浅出设计模式——模板方法模式(Template Method Pattern)
模式动机 模板方法模式是基于继承的代码复用基本技术,模板方法模式的结构和用法也是面向对象设计的核心之一.在模板方法模式中,可以将相同的代码放在父类中,而将不同的方法实现放在不同的子类中.在模板方法模式 ...
随机推荐
- 为什么JSP会比Beetl慢
转自:http://my.oschina.net/xiandafu/blog/475740 JSP是预编译成class的,然后模板渲染里比Beetl慢很多,文章从JSP静态文本处理不足,以及JSTL实 ...
- C语言 字符串处理函数 转自 http://blog.chinaunix.net/uid-25885064-id-3175049.html
C字符串处理函数 2012-04-13 18:14:16 分类: C/C++ void *memccpy (void *dest, const void *src, int c, size_t n) ...
- MAMP pro mac 本地集成环境 php sal apache等集成软件
http://www.sdifen.com/mamppro411.html 已存在我的百度云盘 安装后,打开 MAMP 第一步:配置启动和停止选项 默认启动项.默认停止项,只需要勾选: 1.Star ...
- [html][easyui]DataGrid 绑定
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- Java 序列化接口Serializable详解
一个对象序列化的接口,一个类只有实现了Serializable搜索接口,它的对象才是可序列化的.因此如果要序列化某些类的对象,这些类就必须实现Serializable接口.而实际上,Serializa ...
- struts1的一个简单登陆功能
Login.jsp: <form action="<%= request.getContextPath() %>/login.do" method="p ...
- vconsole使用
<html> <head> <meta http-equiv="Content-Type" content="text/html; char ...
- (转 留存)Windows环境下的NodeJS+NPM+GIT+Bower安装配置步骤
Windows环境下的NodeJS+NPM+GIT+Bower安装配置步骤 标签: NodeJSnpmbower 2015-07-17 16:38 3016人阅读 评论(0) 收藏 举报 分类: G ...
- zookeeper 节点讲解以及实际项目运用
转自:https://www.jianshu.com/p/86acf1df6cdd 前言:最近工作不是很忙,本应该乘着闲暇的时间看书的,之前每天晚上都要翻翻的,可是自己竟然迷恋上了王晓磊 写的 卑鄙的 ...
- binary tree
一.中序线索化 二叉树节点定义: class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; int isle ...