public abstract class SoyaMilk {
//模版方法 可以做成finaL,不让子类去覆盖
final void make(){
select();
if(customerWantCondiments()){
addCondiments();
}
soak();
beat();
}
void select(){
System.out.println("第一步,请选择好的新鲜黄豆");
}
//添加不同的配料,抽象方法,子类具体实现
abstract void addCondiments();
//浸泡
void soak(){
System.out.println("第三部,黄豆和配料开始浸泡,需要三个小时");
}
void beat(){
System.out.println("第四步:黄豆和配料放到豆浆机去打碎");
}
//钩子方法,决定是否需要添加配料
boolean customerWantCondiments(){
return true;
}
}
public class ReadBeanSoyaMilk extends SoyaMilk{
@Override
void addCondiments() {
System.out.println("加入上好的红豆");
}
}
public class PureSoyaMilk extends SoyaMilk{
@Override
void addCondiments() {
System.out.println("2112");
}
@Override
boolean customerWantCondiments() {
return false;
}
}
public class PeanutSoyaMilk extends SoyaMilk{
@Override
void addCondiments() {
System.out.println("加入上好的花生");
}
}
public class Cilent {
public static void main(String[] args) {
//制作红豆豆浆
SoyaMilk readBeanSoyaMilk = new ReadBeanSoyaMilk();
readBeanSoyaMilk.make();
//制作花生豆浆
SoyaMilk soyaMilk = new PeanutSoyaMilk();
soyaMilk.make();
//制作纯豆浆
SoyaMilk ps = new PureSoyaMilk();
ps.make();
}
}