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

  • 相关阅读:
    百万级数据迁移方案测评小记
    EFCore-一对一配置外键小记2
    mpvue实战-手势滑动导航栏
    React-Native WebView使用本地js,css渲染html
    Dubbo测试环境服务调用隔离这么玩对么
    Kitty中的动态线程池支持Nacos,Apollo多配置中心了
    嘘!异步事件这样用真的好么?
    一时技痒,撸了个动态线程池,源码放Github了
    熬夜之作:一文带你了解Cat分布式监控
    这个Maven依赖的问题,你敢说你没遇到过
  • 原文地址:https://www.cnblogs.com/mengjianzhou/p/5986814.html
Copyright © 2011-2022 走看看