策略设计模式在Android开发中的应用

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
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • javascript设计模式与开发实践 设计模式 每个设计模式我们需要从三点问题入手: 定义 作用 用法与实现 单...
    穿牛仔裤的蚊子阅读 4,296评论 0 13
  • 1.初识策略模式 定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户...
    王侦阅读 1,498评论 0 3
  • 概念及定义 概念在完成某一功能时,有时需要根据不同环境采取不同的策略或行为。将这些不同的策略或行为(称为算法)一一...
    maxwellyue阅读 587评论 0 0
  • 我手握你的温柔,伴你远走。 ————题记 ...
    张不韪阅读 426评论 0 0
  • 兄长不惑逝他乡, 妹心憔悴思过往。 回归星辰位何方, 举目四眺心怅茫。
    筱雨含香阅读 126评论 0 0