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)
模式动机 模板方法模式是基于继承的代码复用基本技术,模板方法模式的结构和用法也是面向对象设计的核心之一.在模板方法模式中,可以将相同的代码放在父类中,而将不同的方法实现放在不同的子类中.在模板方法模式 ...
随机推荐
- 【转】Java transient关键字使用小记
哎,虽然自己最熟的是Java,但很多Java基础知识都不知道,比如transient关键字以前都没用到过,所以不知道它的作用是什么,今天做笔试题时发现有一题是关于这个的,于是花个时间整理下transi ...
- C++ 函数特性_函数重载
函数重载 在相同作用域内 用同一函数名定义的多个函数: 参数个数和参数类型不同 int getMax(int x,int y,int z) // 函数名相同都是 getMax() { // to do ...
- json中key大小写转换
最近工作中遇到json格式的字符串中的key为大写的,需要转换成小写的来解析,开始想使用正则来替换,结果不是很方便,后来考虑把JSONObject重新来封装. 如下json格式:{PWACHECKIN ...
- ThreadCachedInt
folly/ThreadCachedInt.h High-performance atomic increment using thread caching. folly/ThreadCachedIn ...
- selenium webdriver——JS操作日历控件
一般的日期控件都是input标签下弹出来的,如果使用webdriver 去设置日期, 1. 定位到该input 2. 使用sendKeys 方法 比如 但是,有的日期控件是readonly的 比如12 ...
- ASPxGridView删除、添加、修改成功后,弹出提示对话框的方法
分为几步: 1.在aspx文件中添加 function EndCallBack(s, e) { if (s.cpAlertMsg != "" && s.cpA ...
- 迷你MVVM框架 avalonjs 0.93发布
这段时间吸取@limodou, @东灵等人的意见,做了以下改进 重构isArrayLike,提高avalon.each的性能,原来avalon.each是依赖于isArrayLike来判定是循环普通对 ...
- kubelet disk 压力
systemctl stop docker mv /var/lib/docker /data/lib ln -s /data/lib/docker /var/lib/docker systemctl ...
- 非root用户使用1024以下端口
如果你有一个最新的内核,确实有可能使用它作为非root用户启动服务,但绑定低端口.最简单有效的办法是: #setcap 'cap_net_bind_service=+ep' /path/to/pr ...
- 【转载】Javascript里面的线程和异步
JavaScript引擎是单线程运行的,浏览器无论在什么时候都只且只有一个线程在运行JavaScript程序. 参考这篇文章 http://www.ruanyifeng.com/blog/2012/1 ...