模板类
package com.ietree.designpattern.template; /** * 模板类 * * @author Root */ public abstract class Shopping { // 模板方法 public void buyGoods() { userLogin(); buy(); pay(); } // 子类不能重写的方法 public final void userLogin() { System.out.println("用户登录"); } // 子类必须实现的方法 public abstract void buy(); // 钩子方法 public void pay() { System.out.println("使用银联卡支付"); } }
实现类:
package com.ietree.designpattern.template; public class ShoesShopping extends Shopping { @Override public void buy() { System.out.println("购买鞋子"); } @Override public void pay() { System.out.println("使用支付宝支付"); } }
package com.ietree.designpattern.template; public class ClothesShopping extends Shopping { @Override public void buy() { System.out.println("购买西装"); } }
测试类:
package com.ietree.designpattern.template.test; import com.ietree.designpattern.template.ClothesShopping; import com.ietree.designpattern.template.ShoesShopping; import com.ietree.designpattern.template.Shopping; public class MyTest { public static void main(String[] args) { Shopping shoesShopping = new ShoesShopping(); shoesShopping.buyGoods(); System.out.println("-------------------"); Shopping clothesShopping = new ClothesShopping(); clothesShopping.buyGoods(); } }
程序输出结果:
用户登录 购买鞋子 使用支付宝支付 ------------------- 用户登录 购买西装 使用银联卡支付