设计模式实战:模版方法

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);
        }
    }
}

具体子类(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;
  }
}

这是一个操作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;
  }

}

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


/**
 * 这个定时任务用于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);
    }
  }
}


/**
 * 这个定时任务用于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);
    }
  }
}

4 优缺点

优点:

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

缺点:

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

5 适用场景

  • 算法的整体步骤很固定,但其中个别部分易变时,这时候可以使用模板方法模式,将容易变的部分抽象出来,供子类实现。
  • 需要通过子类来决定父类算法中某个步骤是否执行,实现子类对父类的反向控制。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值