设计模式之六--策略模式

前言

在现实生活中,我们想去某个地方的话。一般会在地图APP中输入起点和终点。然后选择出行方式,地图APP则会为我们规划出路线来。比如开车,骑自行车,公共交通(地铁,公交车),打车,坐火车等等。根据不同的情况,选择不同的出行方式。如果是省内,路途较近,考虑自己开车。如果是市内,又有地铁,公交直达的话,考虑公共交通。同样,在软件开发的过程中,如果达到一种目的,有多种方式,而每种方式可以封装成一种算法,我们就可以使用策略模式来动态选择使用方式。

出行方式选择

是什么

策略模式:定义可相互替换的一系列算法类,将算法封装起来,使得算法独立于客户而变化。又叫政策模式,是一种对象行为型模式。

为什么

为什么要使用策略模式呢?那我们想想如果不使用的话有什么问题呢。就以公共交通计算出行费用为例。如图所示,公交出行的费用计算规则是10公里内2块钱,超过10公里,每加1块钱可以座5公里。而地铁的规则则是6公里内3块钱,6-12公里内4块钱,12-22公里5块钱,22-32公里6块钱,超过32公里,每加1块钱可以座20公里

公交出行费用计算规则

 

公交出行费用计算规则

package work.johntsai.designpattern.strategy;

public class TrafficCostCalculate {

    public static final int TYPE_BUS = 1;
    public static final int TYPE_METRO = 2;

    private int getBusCost(int distance) {
        if (distance <= 0) {
            throw new IllegalArgumentException();
        } else if (distance <= 10) {
            return 2;
        } else {
            int exceed = distance - 10;
            return 2 + exceed / 5 + (exceed % 5 > 0 ? 1 : 0);
        }
    }

    private int getMetroCost(int distance) {
        if (distance <= 0) {
            throw new IllegalArgumentException();
        } else if (distance <= 6) {
            return 3;
        } else if (distance <= 12) {
            return 4;
        } else if (distance <= 22) {
            return 5;
        } else if (distance <= 32) {
            return 6;
        } else {
            int exceed = distance - 32;
            return 6 + exceed / 20 + exceed % 20 > 0 ? 1 : 0;
        }
    }

    public int getTrafficCost(int type, int distance) {
        switch (type){
            case TYPE_BUS:
                return getBusCost(distance);
            case TYPE_METRO:
                return getMetroCost(distance);
            default:
                throw new IllegalArgumentException();
        }
    }

    public static void main(String[] args) {

        TrafficCostCalculate costCalculate = new TrafficCostCalculate();
        int buscost = costCalculate.getTrafficCost(TYPE_BUS,18);
        int metrocost = costCalculate.getTrafficCost(TYPE_METRO,18);

        System.out.println("18公里公交花费"+buscost+"元");
        System.out.println("18公里地铁花费"+metrocost+"元");

    }

}


上面的代码包含了公交和地铁两种公共交通的价格计算的方式。如果想新增一种出租车的计算,则需要直接修改这个类的代码,导致后期难以维护。所以显然不符合开闭原则TrafficCostCalculate这个类既负责计算公交,也负责计算地铁,也不符合单一指责原则

怎么做

那么接下来试着用策略模式优化上面的代码,在优化之前,先要学习一些概念。

 

UML类图

如图所示:
策略模式主要有以下三种角色:

  • 1.Strategy:抽象策略类。声明了抽象方法,是所有策略类的父类。
  • 2.StrategyA:具体策略类。实现了抽象策略类中定义的抽象方法。
  • 3.Context:环境类,用于操作策略的上下文环境。

首先实现的是抽象策略类,通过给定出行举例,计算出价格:

package work.johntsai.designpattern.strategy;

/**
 * 出行价格抽象策略类
 */
public interface CostStrategy {

    /**
     * 抽象方法,给定距离,计算出出行价格
     * @param distance 出行距离
     * @return 价格
     */
     int calculate(int distance);

}

然后就要实现公交和地铁的具体策略类:

package work.johntsai.designpattern.strategy;

/**
 * 公交出行价格策略类
 */
public class BusCostStrategy implements CostStrategy {
    @Override
    public int calculate(int distance) {
        if (distance <= 0) {
            throw new IllegalArgumentException();
        } else if (distance <= 10) {
            return 2;
        } else {
            int exceed = distance - 10;
            return 2 + exceed / 5 + (exceed % 5 > 0 ? 1 : 0);
        }
    }
}
package work.johntsai.designpattern.strategy;

/**
 * 地铁出行价格策略类
 */
public class MetroCostStrategy implements CostStrategy {
    @Override
    public int calculate(int distance) {
        if (distance <= 0) {
            throw new IllegalArgumentException();
        } else if (distance <= 6) {
            return 3;
        } else if (distance <= 12) {
            return 4;
        } else if (distance <= 22) {
            return 5;
        } else if (distance <= 32) {
            return 6;
        } else {
            int exceed = distance - 32;
            return 6 + exceed / 20 + exceed % 20 > 0 ? 1 : 0;
        }
    }
}

接下来就是要实现持有抽象策略对象的环境类了:

package work.johntsai.designpattern.strategy;

/**
 * 环境类
 * 持有一个抽象策略对象,用于定义采用的策略
 */
public class TrafficCalculateContext {

    private CostStrategy costStrategy;

    public void setCostStrategy(CostStrategy costStrategy){
        this.costStrategy = costStrategy;
    }

    public int calculate(int distance){
        if(this.costStrategy != null){
            return this.costStrategy.calculate(distance);
        }else {
            throw new RuntimeException("计算交通出行价格之前,必须要指定出行方式");
        }
    }

}

最后来测试一下具体的客户端使用:

package work.johntsai.designpattern.strategy;

public class Client {

    public static void main(String[] args) {

        TrafficCalculateContext calculateContext = new TrafficCalculateContext();

        calculateContext.setCostStrategy(new BusCostStrategy());
        int busCost = calculateContext.calculate(18);

        calculateContext.setCostStrategy(new MetroCostStrategy());
        int metroCost = calculateContext.calculate(18);

        System.out.println("18公里公交花费" + busCost + "元");
        System.out.println("18公里地铁花费" + metroCost + "元");

    }

}

通过以上策略模式的改写,我们将一个TrafficCostCalculate类拆分成了CostStrategy,BusCostStrategy,MetroCostStrategy,TrafficCalculateContext四个类。当我们想计算其他出行方式的价格时,我们只需要新增一个对应的策略类去实现calculate方法即可。不需要修改已有的代码。而且每个类只负责相应的职责,没有上帝类的存在。



链接:https://www.jianshu.com/p/4c3bc2888692

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值