• Java设计模式(七) 模板模式-使用钩子


    1,模板类

    package com.pattern.template;
    
    public abstract class CaffeineBeverageWithHook {
    	
    	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(){
    		return true;
    	}
    
    }
    

    2,模板的子类实现类

    package com.pattern.template;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    
    public class CoffeeWithHook extends CaffeineBeverageWithHook{
    
    	/** 
    	 * @see com.pattern.template.CaffeineBeverageWithHook#brew()
    	 */
    	@Override
    	void brew() {
    		System.out.println("Dripping Coffee through filter");
    	}
    
    	/** 
    	 * @see com.pattern.template.CaffeineBeverageWithHook#addCondiments()
    	 */
    	@Override
    	void addCondiments() {
    		System.out.println("Adding Sugar and Milk");
    	}
    	
    	public boolean customerWantsCondiments(){
    		String answer = getUserInput();
    		
    		if(answer.toLowerCase().startsWith("y")){
    			return true;
    		} else{
    			return false;
    		}
    	}
    	
    	private String getUserInput(){
    		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 e) {
    			System.out.println("IO Exception!");
    		}
    		
    		if(answer == null){
    			return "no";
    		}
    		return answer;
    	}
    
    }
    
    

    3,测试类

    package com.pattern.template;
    
    public class BeverageTestDrive {
    	
    	public static void main(String[] args) {
    
    		CoffeeWithHook coffeeHook = new CoffeeWithHook();
    		System.out.println("
    Making tea...");
    		coffeeHook.prepareRecipe();
    	}
    }

    4,输出结果:

    Making tea...
    Boiling water
    Dripping Coffee through filter
    Pouring into cup
    Would you like milk and sugar with your coffee (y/n)?
    y
    Adding Sugar and Milk

  • 相关阅读:
    奶牛编号(Cowids) [NOIP模拟]
    天天爱跑步 [NOIP2016]
    部落冲突
    狡猾的商人 [HNOI2005] [一题双解]
    最长公共子序列-LCS问题 (LCS与LIS在特殊条件下的转换) [洛谷1439]
    LeetCode 2. Add Two Numbers
    LeetCode 1. Two Sum
    LeetCode 91. Decode Ways
    LeetCode 516. Longest Palindromic Subsequence
    什么是马拉车算法(Manacher's Algorithm)?
  • 原文地址:https://www.cnblogs.com/mengjianzhou/p/5986814.html
Copyright © 2020-2023  润新知