• 设计模式实战:模版方法


    1.模版方法概述

    面向对象程序设计过程中,程序员常常会遇到这种情况:设计一个系统时知道了算法所需的关键步骤,而且确定了这些步骤的执行顺序,但某些步骤的具体实现还未知,或者说某些步骤的实现与具体的环境相关。
    例如,去银行办理业务一般要经过以下4个流程:取号、排队、办理具体业务、对银行工作人员进行评分等,其中取号、排队和对银行工作人员进行评分的业务对每个客户是一样的,可以在父类中实现,但是办理具体业务却因人而异,它可能是存款、取款或者转账等,可以延迟到子类中实现。
    定义:
    定义一个操作中的算法骨架,而将算法的一些步骤延迟到子类中,使得子类可以不改变该算法结构的情况下重定义该算法的某些特定步骤。

    2.项目中的具体需求

    项目中mongodb有多个日志类的表数据过多,不仅查询影响性能、还增加了存储成本,决定这些表只保留6个月的数据,大于6个月在2年零6个月内的数据放在备份表。超过两年零6个月的数据直接删除。
    这里拿两个表举例,分别是:
    nativeDO
    successDO
    备份表名称定义为:
    nativeDO_history
    successDO_history

    这些表移动数据的步骤是固定的,分别为:原始表两年零6个月的直接删除->把原始表6个月外两年零6个月内的移动到历史表->删除历史表两年零6个月后的数据。我们把这个固定的步骤抽象出来。

    3.代码实现

    抽象类(Abstract Class):负责给出一个算法的轮廓和骨架。它由一个模板方法和若干个基本方法构成。

    • 模板方法:定义了算法的骨架,按某种顺序调用其包含的基本方法。
    
    @Slf4j
    public abstract class HistoricalDataAbstractClass<T> {
    
        /**
       * 两年零6个月的直接删除
       *
       * @param timeYear
       * @param time
       * @return
       */
        protected abstract void delete(Long timeYear, Long time);
    
    
        /**
       * 6个月外两年零6个月内的移动到历史表
       * @param pageSize
       * @param time
       * @return
       */
        protected abstract PageResult<T> mobileData(Integer pageSize, Long time);
    
        /**
       * 删除历史表两年零6个月后的数据
       * @param timeYear
       * @param time
       */
        protected abstract void deleteByHistoryTable(Long timeYear, Long time);
    
        public final void historicalData(String jobName) {
            Integer pageSize = 2000;
            // 6个月前的时间戳,今日 2023-08-18 00:00:00那么结果就是2023-02-18 00:00:00
            long time =
            DateUtil.offset(
                DateUtil.parse(DateUtil.today()),
                DateField.MONTH,
                -BaseConstant.SAVE_DATA_FOR_SEVERAL_MONTHS)
            .getTime();
            // 2年6个月前的时间戳
            long timeYear =
            DateUtil.offset(
                DateUtil.parse(DateUtil.formatDate(new Date(time))),
                DateField.YEAR,
                -BaseConstant.SAVE_DATA_FOR_SEVERAL_YEAR)
            .getTime();
            try {
                //两年零6个月的直接删除
                delete(timeYear, time);
                //6个月外两年零6个月内的移动到历史表
                PageResult<T> page = mobileData(pageSize, time);
                Long total = page.getTotal();
                while (total > 0) {
                    page = mobileData(pageSize, time);
                    total = page.getTotal();
                    //停止
                    if (page.getList().size() < pageSize) {
                        break;
                    }
                }
                //删除历史表两年零6个月后的数据
                deleteByHistoryTable(timeYear, time);
            } catch (Exception e) {
                log.error("historicalData " + jobName + " error", e);
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

    具体子类(Concrete Class):实现抽象类中所定义的抽象方法。
    这是一个操作nativeDO表的具体子类

    @Slf4j
    @Service
    public class NativeHookRecordHistoricalDataServiceImpl
        extends HistoricalDataAbstractClass<NativeHookRecordDO>{
    
      @Resource private INativeHookRecordDbService nativeHookRecordDbService;
    
      /**
       * 两年零6个月的直接删除
       * @param timeYear
       * @param time
       */
      @Override
      protected void delete(Long timeYear, Long time) {
        log.info(
            "historicalData NativeHookRecordHistoricalDataJob Data processing time point:{}", time);
        nativeHookRecordDbService.createHistoricalDataCollection();
        DeleteResult nativeHookRecordDeleteResult = nativeHookRecordDbService.deleteByTime(timeYear);
        log.info(
            "historicalData NativeHookRecordHistoricalDataJob nativeHookRecordDeleteResult:{},time:{},Delete before this time:{}",
            nativeHookRecordDeleteResult,
            time,
            timeYear);
      }
    
      /**
       * 删除历史表两年零6个月后的数据
       * @param timeYear
       * @param time
       */
      @Override
      protected void deleteByHistoryTable(Long timeYear, Long time) {
        DeleteResult nativeHookRecordHistoryDeleteResult =
            nativeHookRecordDbService.deleteByHistoryTable(timeYear);
        log.info(
            "historicalData NativeHookRecordHistoricalDataJob nativeHookRecordHistoryDeleteResult:{},time:{},Delete before this time:{}",
            nativeHookRecordHistoryDeleteResult,
            time,
            timeYear);
      }
    
      /**
       * 6个月外两年零6个月内的移动到备份表
       * @param pageSize
       * @param time
       * @return
       */
      @Override
      protected PageResult<NativeHookRecordDO> mobileData(Integer pageSize, Long time) {
        PageResult<NativeHookRecordDO> page =
            nativeHookRecordDbService.findPagByTime(time, 1, pageSize);
        nativeHookRecordDbService.deleteById(page.getList());
        nativeHookRecordDbService.insertMultiple(page.getList());
        return page;
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    这是一个操作successDO表的具体子类

    
    @Slf4j
    @Service
    public class SuccessHookAddFieldServiceImpl 
    	extends HistoricalDataAbstractClass<SuccessHookDO>{
    
      @Resource private SuccessHookDbServiceImpl successHookDbService;
    
      /**
       * 两年零6个月的直接删除
       * @param timeYear
       * @param time
       */
      @Override
      protected void delete(Long timeYear, Long time) {
        log.info("historicalData SuccessHookHistoricalDataJob Data processing time point:{}", time);
        successHookDbService.createHistoricalDataCollection();
        // 超过2年零6个月的数据直接删除
        DeleteResult successHookDeleteResult = successHookDbService.deleteByTime(timeYear);
        log.info(
            "historicalData SuccessHookHistoricalDataJob successHookDeleteResult:{},time:{},Delete before this time:{}",
            successHookDeleteResult,
            time,
            timeYear);
      }
    
      /**
       * 删除历史表两年零6个月后的数据
       * @param timeYear
       * @param time
       */
      @Override
      protected void deleteByHistoryTable(Long timeYear, Long time) {
        DeleteResult successHookHistoryDeleteResult =
            successHookDbService.deleteByTimeAndCollectionName(timeYear);
        log.info(
            "historicalData SuccessHookHistoricalDataJob successHookHistoryDeleteResult:{},time:{},Delete before this time:{}",
            successHookHistoryDeleteResult,
            time,
            timeYear);
      }
    
      /**
       * 6个月外两年零6个月内的移动到备份表
       * @param pageSize
       * @param time
       * @return
       */
      @Override
      protected PageResult<SuccessHookDO> mobileData(Integer pageSize, Long time) {
        PageResult<SuccessHookDO> page = successHookDbService.findPagByTime(time, 1, pageSize);
        successHookDbService.deleteById(page.getList());
        successHookDbService.insertMultiple(page.getList());
        return page;
      }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    最后我们通过定时任务来调用

    
    /**
     * 这个定时任务用于nativeDO表6个月的数据保存再nativeDO表, 6个月外两年零6一个月内的保存在nativeDO_history表
     * 两年零6一个月外的直接删除
     */
    @Slf4j
    @Data
    @Component
    @EqualsAndHashCode(callSuper = true)
    public class NativeHookRecordHistoricalDataJob extends QuartzJobBean {
    
      @Resource private NativeHookRecordHistoricalDataServiceImpl nativeHookRecordHistoricalDataService;
    
      @Override
      protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        try {
          log.info("historicalData NativeHookRecordHistoricalDataJob start.");
          nativeHookRecordHistoricalDataService.historicalData("NativeHookRecordHistoricalDataJob");
          log.info("historicalData NativeHookRecordHistoricalDataJob end.");
        } catch (Exception e) {
          log.error("historicalData NativeHookRecordHistoricalDataJob error.", e);
        }
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    
    /**
     * 这个定时任务用于successDO表6个月的数据保存再successDO表, 6个月外两年零6一个月内的保存在successDO_history表
     * 两年零6一个月外的直接删除
     */
    @Slf4j
    @Data
    @Component
    @EqualsAndHashCode(callSuper = true)
    public class SuccessHookHistoricalDataJob extends QuartzJobBean {
    
      @Resource private SuccessHookAddFieldServiceImpl successHookAddFieldService;
    
      @Override
      protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("historicalData SuccessHookHistoricalDataJob start.");
        try {
          successHookAddFieldService.historicalData("SuccessHookHistoricalDataJob");
          log.info("historicalData SuccessHookHistoricalDataJob end.");
        } catch (Exception e) {
          log.error("historicalData SuccessHookHistoricalDataJob error.", e);
        }
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    4 优缺点

    优点:

    • 提高代码复用性
      将相同部分的代码放在抽象的父类中,而将不同的代码放入不同的子类中。
    • 实现了反向控制
      通过一个父类调用其子类的操作,通过对子类的具体实现扩展不同的行为,实现了反向控制 ,并符合“开闭原则”。

    缺点:

    • 对每个不同的实现都需要定义一个子类,这会导致类的个数增加,系统更加庞大,设计也更加抽象。
    • 父类中的抽象方法由子类实现,子类执行的结果会影响父类的结果,这导致一种反向的控制结构,它提高了代码阅读的难度。

    5 适用场景

    • 算法的整体步骤很固定,但其中个别部分易变时,这时候可以使用模板方法模式,将容易变的部分抽象出来,供子类实现。
    • 需要通过子类来决定父类算法中某个步骤是否执行,实现子类对父类的反向控制。
  • 相关阅读:
    微信小程序开发源码系统集合版:含15大类别小程序功能 包升级更新
    一个M阶B树具有特性
    电容式雨雪传感器
    Verilog基础:阻塞/非阻塞赋值
    LeetCode 算法:LRU 缓存 c++
    网络安全(黑客)自学
    C# XML基础入门(XML文件内容增删改查清)
    cnpm安装步骤
    刘二大人 PyTorch深度学习实践 笔记 P5 用PyTorch实现线性回归
    刷题学习记录
  • 原文地址:https://blog.csdn.net/qq_25292419/article/details/132922628