1、问题描述
小明喜欢品尝不同类型的咖啡,她发现每种咖啡的制作过程有一些相同的步骤,他决定设计一个简单的咖啡制作系统,使用模板方法模式定义咖啡的制作过程。系统支持两种咖啡类型:美式咖啡(American Coffee)和拿铁(Latte)。
咖啡制作过程包括以下步骤:
- 研磨咖啡豆 Grinding coffee beans
- 冲泡咖啡 Brewing coffee
- 添加调料 Adding condiments
其中,美式咖啡和拿铁的调料添加方式略有不同, 拿铁在添加调料时需要添加牛奶Adding milk
输入示例
1
2
输出示例
Making American Coffee:
Grinding coffee beans
Brewing coffee
Adding condiments
Making Latte:
Grinding coffee beans
Brewing coffee
Adding milk
Adding condiments
2、模版方法模式
方法模版类:定义了模版方法有哪些抽象方法,该抽象方法等具体的算法实现
具体方法:实现模版类的抽象方法
3、代码
import com.sun.java.accessibility.util.TopLevelWindowListener;import java.util.*;public class Main{public static void main(String[] args){Scanner sc=new Scanner(System.in);while(sc.hasNextInt()){int tag=sc.nextInt();if(tag==1){System.out.println("Making American Coffee:");AmericanCoffee a=new AmericanCoffee();a.template();}else if(tag==2){System.out.println("Making Latte:");LatteCoffee l=new LatteCoffee();l.template();}}}
}abstract class coffee{public void template(){Grind();Brew();Add();}abstract void Grind();abstract void Brew();abstract void Add();
}class AmericanCoffee extends coffee{@Overridevoid Grind() {System.out.println("Grinding coffee beans");}@Overridevoid Brew() {System.out.println("Brewing coffee");}@Overridevoid Add() {System.out.println("Adding condiments");}
}class LatteCoffee extends coffee{@Overridevoid Grind() {System.out.println("Grinding coffee beans");}@Overridevoid Brew() {System.out.println("Brewing coffee");}@Overridevoid Add() {System.out.println("Adding milk");System.out.println("Adding condiments");}
}