publicabstractclassBeverage{publicvoidprepareBeverage(){boilWater();brew();pourInCup();addCondiment();}privatevoidpourInCup(){System.out.println("Pouring in cup");}privatevoidboilWater(){System.out.println("Boiling water");}protectedabstractvoidbrew();protectedabstractvoidaddCondiment();}
publicclassTeaextendsBeverage{@Overrideprotectedvoidbrew(){System.out.println("Stepping the tea");}@OverrideprotectedvoidaddCondiment(){System.out.println("Adding lemon");}}
咖啡类,继承自模板方法类
1234567891011
publicclassCoffeeextendsBeverage{@Overrideprotectedvoidbrew(){System.out.println("Dripping coffee through filter");}@OverrideprotectedvoidaddCondiment(){System.out.println("Adding sugar and milk");}}
publicabstractclassBeverage{publicvoidprepareBeverage(){boilWater();brew();pourInCup();if(customerRequiresCondiment()){addCondiment();}}privatevoidpourInCup(){System.out.println("Pouring in cup");}privatevoidboilWater(){System.out.println("Boiling water");}protectedbooleancustomerRequiresCondiment(){returntrue;}protectedabstractvoidbrew();protectedabstractvoidaddCondiment();}
2、红茶,需要询问
12345678910111213141516171819202122
publicclassBlackTeaextendsBeverage{@Overrideprotectedvoidbrew(){System.out.println("Brew black tea");}@OverrideprotectedvoidaddCondiment(){System.out.println("Add sugar");}@OverridepublicbooleancustomerRequiresCondiment(){Stringflag=newScanner(System.in).nextLine();if(flag.equalsIgnoreCase("y")){returntrue;}else{returnfalse;}}}
Boiling water
Stepping the tea
Pouring in cup
Adding lemon
Boiling water
Dripping coffee through filter
Pouring in cup
Adding sugar and milk
Boiling water
Brew black tea
Pouring in cup
y
Add sugar