1. 模式定义
定义一系列的算法,把每一个算法封装起来,并且使它们可相互替换。策略设计模式使得算法可
独立于使用它的客户而独立变化。
2. 策略示例
假如我们要做一款理财产品,有支付宝和微信两个支付渠道,两个渠道的金额算法不一样,这时再来了一个工行支付渠道又或者后面再来多几个渠道,而当每个渠道的金额算法不一样的时候,这时使用策略设计模式将各个渠道的金额算法封装起来,即可条理清晰,万一某个渠道的算法发生改变,也可直接修改该渠道的算法。
假设我们有一原价 100 商品,各个渠道都有优惠,但优惠力道不同,支付宝是优惠是:原价-(原价/10),微信优惠是:// 原价-(原价/20),工行优惠是:原价 - 0.1,那用策略设计模式的写法如下。
定义价格策略接口 IPrice.java
public interface IPrice {
double price(double originPrice);
}
分别三种支付方式实现价格策略接口,具体的策略实现,将金额算法写在其中
public class AliPayPrice implements IPrice {
@Override
public double price(double originPrice) {
// 原价-(原价/10)
BigDecimal discountPrice = new BigDecimal(originPrice).divide(new BigDecimal(10), 2, BigDecimal.ROUND_HALF_UP);
return new BigDecimal(originPrice).subtract(discountPrice).doubleValue();
}
}
public class WechatPayPrice implements IPrice {
@Override
public double price(double originPrice) {
// 原价-(原价/20)
BigDecimal discountPrice = new BigDecimal(originPrice).divide(new BigDecimal(20), 2, BigDecimal.ROUND_HALF_UP);
return new BigDecimal(originPrice).subtract(discountPrice).doubleValue();
}
}
public class GonghangPayPrice implements IPrice {
@Override
public double price(double originPrice) {
// 原价 - 0.1
return originPrice - 0.1d;
}
}
建立上下文角色,用来操作策略的上下文环境,起到承上启下的作用,屏蔽高层模块对策略、算
法的直接访问。
public class PriceContext {
private IPrice iPrice;
public PriceContext(IPrice iPrice) {
this.iPrice = iPrice;
}
public double price(double originPrice) {
return this.iPrice.price(originPrice);
}
}
3. 测试实现
在的开发客户端中,我们可以这样来使用
public class AppClient {
public static void main(String[] args){
double originPrice = 100d;
AliPayPrice aliPayPrice = new AliPayPrice();
PriceContext priceContext = new PriceContext(aliPayPrice);
System.out.println("price = "+ priceContext.price(originPrice)); // 结果:price = 90.00
WechatPayPrice wechatPayPrice = new WechatPayPrice();
priceContext = new PriceContext(wechatPayPrice);
System.out.println("price = "+ priceContext.price(originPrice)); // 结果:price = 95.00
GonghangPayPrice gonghangPayPrice = new GonghangPayPrice();
priceContext = new PriceContext(gonghangPayPrice);
System.out.println("price = "+ priceContext.price(originPrice)); // 结果:price = 99.90
}
}
网友评论