什么是模板模式
处理一类事情,其中处理的过程个数和顺序是固定的,只是局部可能因处理的事情不同,而实现的方式不同。
在程序中即为处理一类事情,处理流程固定,局部算法延时到子类中实现,子类则不改变整体流程处理顺序,只是
局部算法重写,提供多元化处理。
生活中的栗子
饭店后厨提供鱼的多种吃法:酸菜鱼,水煮鱼,松鼠鱼,红烧鱼。
烧鱼的整体流程固定:杀鱼-->切鱼-->准备作料-->烧制-->摆盘-->上菜
只是在烧制环节各有不同分为:酸菜鱼烧制,水煮鱼烧制,松鼠鱼烧制,红烧鱼烧制
项目中的栗子
支付功能的模板模式
查询订单价格-->核对价格-->进行支付(支付宝,微信,银联)-->发货
模板类
public abstract class PayTemplate {
public boolean processPay(String orderId,Double price) {
//1获取订单价格
Double orderPrice = getOrderPrice(orderId);
//2核对价格
boolean priceCoincide = coincidePrice(orderPrice,price);
//3进行支付(支付宝,微信,银联)
if(priceCoincide) {
boolean paySuccess = doPay(price);
if(paySuccess) {
//4发货
boolean sendGoodsSuccess = sendGoods(orderId);
}
}
return true;
}
protected double getOrderPrice(String orderId) {
System.out.println("根具订单id:"+orderId+"获取订单总价");
return 100D;
}
protected boolean coincidePrice(Double orderPrice,Double price) {
System.out.println("订单总价与支付价格对比校验");
return orderPrice==price;
}
protected abstract boolean doPay(Double price);
protected boolean sendGoods(String orderId) {
System.out.println(orderId+"发货成功");
return true;
}
}
阿里支付实现
public class AliPay extends PayTemplate {
@Override
protected boolean doPay(Double price) {
System.out.println("阿里支付成功,金额:"+price);
return true;
}
}
微信支付实现
public class WeChatPay extends PayTemplate {
@Override
protected boolean doPay(Double price) {
System.out.println("微信支付成功,金额:"+price);
return true;
}
}
银联支付
public class UnionPay extends PayTemplate {
@Override
protected boolean doPay(Double price) {
System.out.println("银联支付成功,金额:"+price);
return true;
}
}
特点
流程标准化,局部多元化