Template Method Design Pattern

Type : Behavioral Design Pattern

Summary
Template method pattern defines some steps or sequences of procedure and defers implementations of the procedures to the subclasses to implement.

Details
Template method uses in real life is very common.

For instance we want to order some product online, first we have to select product and then add it to cart, then checkout.

Another example would be when we go to a movie theater,  we first decide the show, buy the ticket and that go to the respective screen to enjoy the movie, and finally leave the theater.

When the work can broken in to sub tasks and order of the tasks are important Template method helps in maintaining that order.

Another example would be our day to day routine. We can break the day in several sequence of tasks that we want to carry out.

DayRoutine : Abstract class which declares some tasks like wakeup(), doBreakFast() gotoBed() etc.
                        To maintain the order it also has a final method doDayTask().  Here doDayTask() is
                        the template method.

WeekDayRoutine : Concrete routine for week day, which extends the DayRoutine class.
WeekEndRoutine : Concrete routine for weekend, which extends the DayRoutine class.

Class Diagram


Sample Code

// abstract class which implements the template method
public abstract class DailyRoutine {

  public final void doDayTask() {
    wakeup();
    doBreakfast();
    doAssignment();
    doEntertainment();
    gotoBed();
  }

  public final void wakeup() {
    System.out.println("Wake Up");
  }

  public abstract void doBreakfast();

  public abstract void doAssignment();

  public abstract void doEntertainment();

  public abstract void gotoBed();
}

public class WeekDayRoutine extends DailyRoutine {

  @Override
  public void doBreakfast() {
    System.out.println(" Eat Veggy weekday Breakfast");
  }

  @Override
  public void doAssignment() {
    System.out.println("Complete School Assignment");
  }

  @Override
  public void doEntertainment() {
    System.out.println("Nothing");
  }

  @Override
  public void gotoBed() {
    System.out.println("Sleep at 9:02 PM");
  }

}

public class WeekendRoutine extends DailyRoutine{

  @Override
  public void doBreakfast() {
    System.out.println(" Eat Protein Breakfast");
  }

  @Override
  public void doAssignment() {
    System.out.println("do Laundry, Iron, and Vaccum");
  }

  @Override
  public void doEntertainment() {
    System.out.println("Watch Netflix");
  }

  @Override
  public void gotoBed() {
    System.out.println("Goto bed at 11:00 PM");
  }

}

Comments

Popular posts from this blog

Converting Java Map to String

Invoking EJB deployed on a remote machine

Difference between volatile and synchronized