话不多说,直接上代码,代码量少,简单易懂,相信大家认真看完会有所收获。
代码示例:
/*** @Author: YuShiwen* @Date: 2020/11/18 3:24 PM* @Version: 1.0*/publicclassTemplateMethodTest { publicstaticvoidmain(String[] args) { BuyAdidasadidas=newBuyAdidas(); adidas.onlineShopping(); System.out.println(); BuyPumapuma=newBuyPuma(); puma.onlineShopping(); } } abstractclassOnlineShoppingTemplate{ publicvoidopenApp(){ System.out.println("打开购物软件!"); } publicabstractvoidbuyGoods(); publicvoidonlinePayment(){ System.out.println("线上付款!"); } // 模板方法,把基本操作组合到一起,子类一般不能重写publicfinalvoidonlineShopping(){ this.openApp(); //具体执行时,挂哪个子类,就执行哪个子类的实现代码this.buyGoods(); this.onlinePayment(); } } classBuyAdidasextendsOnlineShoppingTemplate{ publicvoidbuyGoods() { System.out.println("buy adidas goods"); } } classBuyPumaextendsOnlineShoppingTemplate { publicvoidbuyGoods() { System.out.println("buy puma goods"); } }
输出结果:
打开购物软件!buyadidasgoods线上付款!打开购物软件!buypumagoods线上付款!Processfinishedwithexitcode0