[关闭]
@BertLee 2017-08-17T20:44:12.000000Z 字数 1689 阅读 1221

行为型之模板方法模式

序言

  模板方法模式通过把不变的行为搬移到父类(抽象类),去除了子类中的重复代码;对于不同的子类有不同实现的行为,在父类中声明一些抽象方法来迫使子类实现剩余的逻辑,提高程序的扩展性。
  模板方法有如下几种角色:

模板方法模式

  模板方法模式的结构如下图:



套路:
1. 梳理原类中方法的业务逻辑,抽象出顶级逻辑,形成抽象模板类,模板方法,抽象方法
2. 根据职责划分,创建相关子类,形成具体模板类,形成具体操作方法

  1. /**
  2. * 抽象模板角色-打印机
  3. */
  4. public abstract class Printer {
  5. //模板方法
  6. public final double getAmount(int num){
  7. String printType = getPrinterType();
  8. double paperPrice = getPaperPrice(printType);
  9. return num * paperPrice;
  10. }
  11. //钩子方法
  12. public String getPrinterName(){return null;}
  13. //抽象方法
  14. protected abstract String getPrinterType();
  15. //抽象方法
  16. protected abstract double getPaperPrice(String printerType);
  17. //具体方法
  18. private void print(){
  19. //打印相关业务
  20. }
  21. }
  1. /**
  2. * 具体模板角色-石墨打印机
  3. */
  4. public class GraphitePrinter extends Printer{
  5. @Override
  6. protected String getPrinterType() {
  7. return "石墨打印";
  8. }
  9. @Override
  10. protected double getPaperPrice(String printerType) {
  11. if("石墨打印".equals(printerType)){
  12. return 1;
  13. }else{
  14. throw new RuntimeException("没有" + printerType + "这种类型");
  15. }
  16. }
  17. }
  1. /**
  2. * 具体模板角色-激光打印机
  3. */
  4. public class LaserPrinter extends Printer{
  5. @Override
  6. protected String getPrinterType() {
  7. return "激光打印";
  8. }
  9. @Override
  10. protected double getPaperPrice(String printerType) {
  11. if("激光打印".equals(printerType)){
  12. return 2;
  13. }else{
  14. throw new RuntimeException("没有" + printerType + "这种类型");
  15. }
  16. }
  17. }
  1. /**
  2. * 测试模板方法模式.
  3. */
  4. public class TemplateMethodTest {
  5. @Test
  6. public void testTemplateMethod(){
  7. //1.激光打印3张纸
  8. new LaserPrinter().getAmount(3);
  9. //2.石墨打印3张纸
  10. new GraphitePrinter().getAmount(3);
  11. }
  12. }

吹牛:
1.模板方法模式展现继承复用的可用之地,以往都是采用委派关系来代继承关系
2. 当方法包含了太多的代码时,不妨试着抽取几个类,几个方法,利用模板方法模式重构一下

后记

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注