标签:设计模式
//声明为抽象类,子类必须实现其操作
public abstract class CaffeineBeverage
{
//声明为final,不希望子类覆盖这个方法
final void prepareRecipe()
{
boilWater();
brew();
pourInCup();
addCondiments();
}
//声明为抽象类,子类必须实现其操作
abstract void brew();
abstract void addCondiments();
void boilWater()
{
System.out.println("Boiling water");
}
void pourInCup()
{
System.out.println("Pouring into cup");
}
}
//extends继承
public class Tea extends CaffeineBeverage {
//需要定义抽象方法
public void brew() {
System.out.println("Steeping the tea");
}
public void addCondiments() {
System.out.println("Adding Lemon");
}
}
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;
}
}
public class CoffeeWithHook extends CaffeineBeverageWithHook {
public void brew() {
System.out.println("Dripping Coffee through filter");
}
public 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.print("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;
}
}《Head First 设计模式》学习笔记——模板方法模式,布布扣,bubuko.com
标签:设计模式
原文地址:http://blog.csdn.net/huaxi1902/article/details/28104027