노현진's Blog

Template Method Pattern

Template Method Pattern에 대해 설명하는 페이지입니다.

Posted
Preview Image
By HyunJinNo

Tags

Design Pattern, Java

1. Introduction

  • Purpose
    • Identifies the framework of an algorithm, allowing implementing classes to define the actual behavior.
  • Use When
    • A single abstract implementation of an algorithm is needed.
    • Common behavior among subclasses should be localized to a common class.
    • Parent classes should be able to uniformly invoke behavior in their subclasses.
    • Most or all subclasses need to implement the behavior.

2. Characteristics

  • The template pattern defines the steps of an algorithm and allows the subclasses to implement one or more of the steps.
  • Encapsulates an algorithm by creating a template for it.
  • Defines the skeleton of an algorithm as a set of steps.
  • Some methods of the algorithm have to be implemented by the subclasses– these are abstract methods in the super class.
  • The subclasses can redefine certain steps of the algorithm without changing the algorithm’s structure.
  • Some steps of the algorithm are concrete methods defined in the super class.
  • Advantages
    • The superclass facilitates reuse of methods.
    • Code changes will occur in only one place.

3. Hook Method

  • A hook is a method that is declared in the abstract class, but only given an empty or default implementation.

4. How to Use (Example)

  • Superclass

    java
    1public abstract class CaffeineBeverage {
    2    public void final prepareRecipe() {
    3        boilWater();
    4        brew();
    5        pourInCup();
    6        if (customerWantsCondiments()) {
    7            addCondiments();
    8        }
    9    }
    10
    11    public void boilWater() {
    12        // implementation
    13    }
    14
    15    public abstract void brew();
    16
    17    public void pourInCup() {
    18        // implementation
    19    }
    20
    21    public abstract void addCondiments();
    22
    23    // hook
    24    public boolean customerWantsCondiments() {
    25        return true;
    26    }
    27}
  • Subclass

    java
    1public class Coffee extends CaffeineBeverage {
    2    @Override
    3    public void brew() {
    4        // implementation
    5    }
    6
    7    @Override
    8    public void addCondiments() {
    9        // implementation
    10    }
    11
    12    @Override
    13    public boolean customerWantsCondiments(char c) {
    14        if (c == 'y') {
    15            return true;
    16        } else {
    17            return false;
    18        }
    19    }
    20}

© HyunJinNo. Some rights reserved.