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{@Overridevoid addCondiments() {System.out.println("加入上好的红豆");}
}
public class PureSoyaMilk extends SoyaMilk{@Overridevoid addCondiments() {System.out.println("2112");}@Overrideboolean customerWantCondiments() {return false;}
}
public class PeanutSoyaMilk extends SoyaMilk{@Overridevoid 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();}
}