Skip to content

Instantly share code, notes, and snippets.

@garudareiga
Created January 13, 2015 07:43
Show Gist options
  • Save garudareiga/37301e7c5175db5d8805 to your computer and use it in GitHub Desktop.
Save garudareiga/37301e7c5175db5d8805 to your computer and use it in GitHub Desktop.
Template Method Design Pattern
public abstract class CaffeineBeverage {
void prepareRecipe() {
boilWater();
brew();
pourInCup();
if (customerWantsCondiments())
addCondiments();
}
abstract void brew();
abstract void addCondiments();
void boilWater() {
System.out.println("Boiling water");
}
void pourInCup() {
System.out.println("Pouring into cup");
}
boolean customerWantsCondiments() { // This is a hook because the subclass can override, but doesn't have to
return true;
}
}
public class Coffee extends CaffeineBeverage {
public void brew() {
System.out.println("Dripping Coffee through filter");
}
public void addCondiments() {
System.out.println("Adding Sugar and Milk");
}
public boolean customerWantsCondiments() {
String answer = getUserInput();
if (answer.equals("y")) return true;
else return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment