Java Design Patterns Template Method Patterns

Introduction

Template Method Patterns create the skeleton of an algorithm, defer steps to subclasses.

The template method allows subclasses to redefine certain steps without changing the algorithm's structure.

Use case

  • Define the steps to layout components and defer the component creation to subclasses.

Example

abstract class UserInterface {
   public void createWindow() {
      drawRectangle();/*from  w w  w. ja v  a  2s  . c  om*/
      drawButton();
      drawContent();
   }

   private void drawRectangle() {
      System.out.println("drawRectangle");
   }

   private void drawButton() {
      System.out.println("drawButton");
   }

   public abstract void drawContent();
}

class AndroidWindow extends UserInterface {
   @Override
   public void drawContent() {
      System.out.println("AndroidWindow");
   }
}

class AppleWindow extends UserInterface {
   @Override
   public void drawContent() {
      System.out.println("AppleWindow");
   }
}

public class Main {
   public static void main(String[] args) {
      UserInterface bs = new AndroidWindow();
      bs.createWindow();
      bs = new AppleWindow();
      bs.createWindow();
   }
}



PreviousNext

Related