1、先说抽象类
抽象类是一种魔化代码的神器,纵观大佬们写的代码,对它的运用可谓是出神入化,令人佩服无比。
为啥说其是魔化神器?
个人感觉,抽象类如果可以好好运用,可以使你的代码看上去入魔入幻,不易理解,但是又能优雅的避免重复代码,实现上下层代码相容,让你的方法逻辑存在于无形之中,堪称牛X。
2、啥是模板方法?
含义:就是把实现某流程的节点方法做抽取,抽取到一个抽象类中,并定义流程入口方法,且定位为final,不可继承,不可修改。然后对于不同的流程细节,分布在子类自行实现。
好处:可以实现算法隐藏,满足开闭原则,可以扩展自定义实现细节流程,但是主流程不能修改;
3、举例
数据集成流程
1、抽象类AbstractIntegrate
/**
* 数据集成模板方法
*/
public abstract class AbstractIntegrate {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected String integrateType;
protected void log(String msg) {
logger.info(integrateType + ":" + msg);
}
protected void log(String msg, Exception ex) {
logger.error(integrateType + ":" + msg, ex);
}
protected abstract void init() throws Exception;
protected abstract void query() throws Exception;
protected abstract void parse() throws Exception;
protected abstract void check() throws Exception;
protected abstract void save() throws Exception;
protected abstract void otherAction() throws Exception;
public final void execute() {
try {
init();
query();
parse();
check();
save();
otherAction();
} catch (Exception e) {
logger.error("execute error", e);
}
}
}
2、采购订单集成类:PurchaseOrderIntegrate
/**
* 采购订单集成
*/
public class PurchaseOrderIntegrate extends AbstractIntegrate {
@Override
protected void init() throws Exception {
this.integrateType = "PurchaseOrder";
}
@Override
protected void query() throws Exception {
log("query");
}
@Override
protected void parse() throws Exception {
log("parse");
}
@Override
protected void check() throws Exception {
log("check");
}
@Override
protected void save() throws Exception {
log("save");
}
@Override
protected void otherAction() throws Exception {
log("otherAction");
}
}
3、工单集成类:WorkOrderIntegrate
/**
* 工单集成
*/
public class WorkOrderIntegrate extends AbstractIntegrate {
@Override
protected void init() throws Exception {
this.integrateType = "WorkOrder";
}
@Override
protected void query() throws Exception {
log("query");
}
@Override
protected void parse() throws Exception {
log("parse");
}
@Override
protected void check() throws Exception {
log("check");
}
@Override
protected void save() throws Exception {
log("save");
}
@Override
protected void otherAction() throws Exception {
log("otherAction");
}
}
4、运行测试
/**
*
*/
public class TemplateTest {
/**
* @param args
*/
public static void main(String[] args) {
AbstractIntegrate integrate1 = new PurchaseOrderIntegrate();
integrate1.execute();
AbstractIntegrate integrate2 = new WorkOrderIntegrate();
integrate2.execute();
}
}
5、结果