自己整理的设计模式案例,如果不对欢迎大家吐槽!
模板方法设计模式
解释一下模板方法模式,就是指:一个抽象类中,有一个主方法,再定义1...n个方法,可以是抽象的,也可以是实际的方法,定义一个类,继承该抽象类,重写抽象方法,通过调用抽象类,实现对子类的调用
具体使用场景
quartz 定时任务举例
public abstract class QuartzJobBean implements Job {
private static final Method getSchedulerMethod;
private static final Method getMergedJobDataMapMethod;
static {
try {
Class jobExecutionContextClass =
QuartzJobBean.class.getClassLoader().loadClass("org.quartz.JobExecutionContext");
getSchedulerMethod = jobExecutionContextClass.getMethod("getScheduler");
getMergedJobDataMapMethod = jobExecutionContextClass.getMethod("getMergedJobDataMap");
}
catch (Exception ex) {
throw new IllegalStateException("Incompatible Quartz API: " + ex);
}
}
/**
* This implementation applies the passed-in job data map as bean property
* values, and delegates to {@code executeInternal} afterwards.
* @see #executeInternal
*/
public final void execute(JobExecutionContext context) throws JobExecutionException {
try {
// Reflectively adapting to differences between Quartz 1.x and Quartz 2.0...
Scheduler scheduler = (Scheduler) ReflectionUtils.invokeMethod(getSchedulerMethod, context);
Map mergedJobDataMap = (Map) ReflectionUtils.invokeMethod(getMergedJobDataMapMethod, context);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValues(scheduler.getContext());
pvs.addPropertyValues(mergedJobDataMap);
bw.setPropertyValues(pvs, true);
}
catch (SchedulerException ex) {
throw new JobExecutionException(ex);
}
executeInternal(context);
}
/**
* Execute the actual job. The job data map will already have been
* applied as bean property values by execute. The contract is
* exactly the same as for the standard Quartz execute method.
* @see #execute
*/
protected abstract void executeInternal(JobExecutionContext context) throws JobExecutionException;
}
上面的executeInternal 方法就是让子类去实现的抽象方法
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class TaskDetailJob extends QuartzJobBean {
private static final Logger log = LoggerFactory.getLogger(TaskDetailJob.class);
/**
* 任务明细定时任务,每天00:10分执行
* 0 10 0 * * ?
*/
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
log.info("定时执行创建红包定时任务" + new Date());
TaskDetailService taskDetailService = getApplicationContext(jobExecutionContext).getBean("taskDetailService", TaskDetailService.class);
taskDetailService.doScheduledJob();
}
private ApplicationContext getApplicationContext(final JobExecutionContext jobexecutioncontext) {
try {
return (ApplicationContext) jobexecutioncontext.getScheduler().getContext().get("applicationContext");
} catch (SchedulerException e) {
log.error("jobexecutioncontext.getScheduler().getContext() error!", e);
throw new RuntimeException(e);
}
}
}