zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    调用google地图
    jQuery放大镜效果
    jQuery拖到效果
    jQuery制作相册
    jQuery ui插件用法
    jQuery写fadeTo方法
    jQuery实现动画效果
    jQuery的slideToggle方法
    控经纬度显示地图与卫星
    像百度那样的智能感知效果
  • 原文地址:https://www.cnblogs.com/mengjianzhou/p/5986814.html
Copyright © 2011-2022 走看看