模版方法模式

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*
* 模版方法模式
* 在一个方法中定义一个算法的骨架,
* 而将一些步骤延迟到子类中.
* 模版方法使得子类可以在不改变算法结构的情况下,
* 重新定义算法中的某些步骤
*/

public class Template {

     public static void main(String[] args) {
  TeaWithHook teaHook = new TeaWithHook();
  CoffeeWithHook coffeeHook = new CoffeeWithHook();
  
  System.out.println( "\nMaking tea...");
  teaHook.prepareRecipe();
  
  System.out.println( "\nMaking coffee...");
  coffeeHook.prepareRecipe();
    }

}

abstract class CaffeineBeverageWithHook{
     //算法骨架
     void prepareRecipe(){
  boilWater();
  brew();
  pourInCup();
   if(customerWantCondiments()){
      addCondiments();
  }
    }
  
     //模版方法
     abstract void brew();
  
     //模版方法
     abstract void addCondiments();
  
     //固有的方法,可以定义为final
     void boilWater(){
  System.out.println( "Boiling water");
    }
  
     //固有的方法,可以定义为final
     void pourInCup(){
  System.out.println( "Pouring into cup");
    }
  
     //钩子方法,子类可以覆盖这个方法,以确定是否需要添加调料
     boolean customerWantCondiments(){
   return true;
    }
}

//具体的实现类
class CoffeeWithHook extends CaffeineBeverageWithHook{
     void brew(){
  System.out.println( "Dripping Coffee through filter");
    }
  
     void addCondiments(){
  System.out.println( "Adding Sugar and Milk");
    }
  
     boolean customerWantCondiments(){
  String answer = gerUserInput();
  
   if (answer.toLowerCase().startsWith( "y")) {
       return true;
  } else {
       return false;
  }
    }
  
     private String gerUserInput(){
  String answer = null;
  
  System.out.println( "Would you like milk and sugar with your coffee (y/n)?");
  
  BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
   try{
      answer = in.readLine();
  } catch (IOException ioe){
      System.err.println( "IO error trying to read your answer");
  }
   if(answer == null){
       return "no";
  }
   return answer;
    }
}

class TeaWithHook extends CaffeineBeverageWithHook{
     void brew(){
  System.out.println( "Dripping Tea through filter");
    }
  
     void addCondiments(){
  System.out.println( "Adding orange");
    }
  
     boolean customerWantCondiments(){
  String answer = gerUserInput();
  
   if (answer.toLowerCase().startsWith( "y")) {
       return true;
  } else {
       return false;
  }
    }
  
     private String gerUserInput(){
  String answer = null;
  
  System.out.println( "Would you like orange with your tea (y/n)?");
  
  BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
   try{
      answer = in.readLine();
  } catch (IOException ioe){
      System.err.println( "IO error trying to read your answer");
  }
   if(answer == null){
       return "no";
  }
   return answer;
    }
}

你可能感兴趣的:(开发,方法,职场,模版,休闲)