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

贴上代码:

模板类:

package cn.template.demo;

/**
 * 模板:其中boilWater()和pourInCup() 方法是共有的, brew()和addCondiments();是需要在子类中自行实现的。
 * customerWantsCondiments()是个钩子,它使得addCondiments()方法可以 根据子类不同的情况来决定是否实现
 * @author wy
 * 
 */
public abstract class CaffeBeverageWithHook {
	public void prepareRecipe() {
		boilWater();
		brew();
		pourInCup();
		if (customerWantsCondiments()) {
			addCondiments();
		}
	}

	abstract void brew();

	abstract void addCondiments();

	void boilWater() {
		System.out.println("boli water....");
	}

	void pourInCup() {
		System.out.println("pouring...");
	}

	// 钩子
	boolean customerWantsCondiments() {
		return true;
	}

}

继承的子类:

package cn.template.demo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
 * 繼承自模板類,重寫了brew()和addCondiments()和customerWantsCondiments()三個方法
 * @author wy
 *
 */
public class CoffeWithHook extends CaffeBeverageWithHook {

	@Override
	void brew() {
		System.out.println("brew...");
	}

	@Override
	void addCondiments() {
		System.out.println("add milk and sugar...");
	}

	@Override
	boolean customerWantsCondiments() {
		String answer = getUserInput();
		if (answer.toLowerCase().startsWith("y")) {
			return true;
		} else {
			return false;
		}
	}

	public String getUserInput() {
		String answer = null;
		System.err.println("Would you like a coffee,Sir?");
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				System.in));
		try {
			answer = reader.readLine();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (answer == null) {
			return "no";
		}
		return answer;
	}
}

测试类:

package cn.template.demo;

public class Test {
	public static void main(String[] args) {
		CoffeWithHook coffeWithHook = new CoffeWithHook();
		coffeWithHook.prepareRecipe();
	}
}
运行之后,控制台打印:

boli water....
brew...
pouring...
Would you like a coffee,Sir?
如果输入:yes,控制台变成

boli water....
brew...
pouring...
Would you like a coffee,Sir?
yes
add milk and sugar...

又加入了milk和sugar;

如果输入:no,控制台变成:

boli water....
brew...
pouring...
Would you like a coffee,Sir?
no
输入no,没有反应,这是钩子在起作用



posted on 2014-01-03 09:37  wyang0126  阅读(133)  评论(0编辑  收藏  举报