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;
02  
03 public abstract class HouseTemplate {
04  
05     //template method, final so subclasses can't override
06     public final void buildHouse(){
07         buildFoundation();
08         buildPillars();
09         buildWalls();
10         buildWindows();
11         System.out.println("House is built.");
12     }
13  
14     //default implementation
15     private void buildWindows() {
16         System.out.println("Building Glass Windows");
17     }
18  
19     //methods to be implemented by subclasses
20     public abstract void buildWalls();
21     public abstract void buildPillars();
22  
23     private void buildFoundation() {
24         System.out.println("Building foundation with cement,iron rods and sand");
25     }
26 }

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;
02  
03 public class WoodenHouse extends HouseTemplate {
04  
05     @Override
06     public void buildWalls() {
07         System.out.println("Building Wooden Walls");
08     }
09  
10     @Override
11     public void buildPillars() {
12         System.out.println("Building Pillars with Wood coating");
13     }
14  
15 }

We could have overridden other methods also, but for simplicity I am not doing that.

GlassHouse.java

01 package com.journaldev.design.template;
02  
03 public class GlassHouse extends HouseTemplate {
04  
05     @Override
06     public void buildWalls() {
07         System.out.println("Building Glass Walls");
08     }
09  
10     @Override
11     public void buildPillars() {
12         System.out.println("Building Pillars with glass coating");
13     }
14  
15 }

Template Method Pattern Client

Let’s test our template method pattern example with a test program.

HousingClient.java

01 package com.journaldev.design.template;
02  
03 public class HousingClient {
04  
05     public static void main(String[] args) {
06  
07         HouseTemplate houseType = new WoodenHouse();
08  
09         //using template method
10         houseType.buildHouse();
11         System.out.println("************");
12  
13         houseType = new GlassHouse();
14  
15         houseType.buildHouse();
16     }
17  
18 }

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
03 Building Wooden Walls
04 Building Glass Windows
05 House is built.
06 ************
07 Building foundation with cement,iron rods and sand
08 Building Pillars with glass coating
09 Building Glass Walls
10 Building Glass Windows
11 House is built.

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.

Reference: Template Method Design Pattern in Java from our JCG partner Pankaj Kumar at the Developer Recipes blog.

Template Method Design Pattern in Java的更多相关文章

  1. 设计模式-模板方法设计模式--Template Method design pattern

    /** * Abstract implementation of the {@link org.springframework.context.ApplicationContext} * interf ...

  2. 设计模式之 - 工厂方法模式 (Factory Method design pattern)

    1. 模式意图:  定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类. 2. 别名(Virtual Constructor) 3. 结构 4. 工厂方法模式C ...

  3. 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 ...

  4. Design Pattern - Service Locator Pattern--转载

    原文地址:http://www.tutorialspoint.com/design_pattern/service_locator_pattern.htm The service locator de ...

  5. Design Pattern —— Prototype /Template Method/Iterator/Composite/Bridge

    Prototype /Template Method/Iterator/Composite/Bridge 为什么把这五种设计模式放一起呢,没什么太高大上的原因,就是因为这五种模式JAVA开发最基本的特 ...

  6. 设计模式 - 模板方法模式(template method pattern) JFrame 具体解释

    模板方法模式(template method pattern) JFrame 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考模板方法模式(templ ...

  7. java设计模式大全 Design pattern samples in Java(最经典最全的资料)

    java设计模式大全 Design pattern samples in Java(最经典最全的资料) 2015年06月19日 13:10:58 阅读数:11100 Design pattern sa ...

  8. java设计模式 模板方法模式Template Method

    设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了可重用代码.让代码更容易被他人理解.保证代码可靠性.毫无疑问,设计模式于己 ...

  9. 深入浅出设计模式——模板方法模式(Template Method Pattern)

    模式动机 模板方法模式是基于继承的代码复用基本技术,模板方法模式的结构和用法也是面向对象设计的核心之一.在模板方法模式中,可以将相同的代码放在父类中,而将不同的方法实现放在不同的子类中.在模板方法模式 ...

随机推荐

  1. opensuse下配置IP、DNS、GATEWAY

    本人物理主机IP描述 IPv4 地址 . . . . . . . . . . . . : 192.168.1.101(首选)子网掩码  . . . . . . . . . . . . : 255.25 ...

  2. java的按值传递与按引用传递

    还是比较混乱 主要看怎么理解了 java没有指针一说是因为jvm将指针给隐藏了起来 说到底还是靠地址 按值传递显然直接将内存空间的内容传递给对方 之后再与传递者无关 引用是在栈空间建一个堆空间对象的映 ...

  3. [正经分析] DAG上dp两种做法的区别——拓扑序与SPFA

    在下最近刷了几道DAG图上dp的题目. 要提到的第一道是NOIP原题<最优贸易>.这是一个缩点后带点权的DAG上dp,它同时规定了起点和终点. 第二道是洛谷上的NOI导刊题目<最长路 ...

  4. springMVC等小知识点记录。。。持续更新

    1.springMVC 项目根路径访问页面配置 <!-- 表示当访问主页时自动转发到index控制器 --> <mvc:view-controller path="/&qu ...

  5. Java 数组类型转字符串类型

    Java手册 String public String() 初始化一个新创建的 String 对象,使其表示一个空字符序列.注意,由于 String 是不可变的,所以无需使用此构造方法. String ...

  6. web开发的功能备忘录

    总体设计 Web项目开发中,我们可以根据不同的功能,将整个系统的功能进行划分.系统功能总体来说可以划分为两个模块:系统的必备功能和逻辑业务功能. 下面主要是分析一下系统的必备功能,所谓系统的必备功能是 ...

  7. 微信小程序从子页面退回父页面时的数据传递 wx.navigateBack()

    我们知道,在微信小程序中,从一个页面转到另一个页面,一般情况下可以通过navigate或redirect时候的url来携带参数,然后在目标页面的onLoad函数参数中获取这些url参数.例如: // ...

  8. 转帖:关于MongoDB你需要知道的几件事

    Henrique Lobo Weissmann 是一位来自于巴西的软件开发者,他是 itexto 公司的联合创始人,这是一家咨询公司.近日,Henrique 在博客上撰文谈到了关于 MongoDB 的 ...

  9. Solr分组聚合查询之Group

    摘要: Solr对结果的分组处理除了facet还可以使用group.Solr的group是根据某一字段对结果分组,将每一组内满足查询的结果按顺序返回. Group对比Facet Group和Facet ...

  10. 将Hive统计分析结果导入到MySQL数据库表中(一)——Sqoop导入方式

    https://blog.csdn.net/niityzu/article/details/45190787 交通流的数据分析,需求是对于海量的城市交通数据,需要使用MapReduce清洗后导入到HB ...