设计模式之Strategy模式

69 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天,点击查看活动详情

Strategy模式

Strategy模式可以整体的替换算法的实现部分。个人认为Strategy可以理解为使用不用的方法解决同一个问题。

示例程序 举一个收银的例子,普通用户打95折,会员打8折,超级会员打6折。

如果在一个函数里面去解决这些问题,那么增加会员类型和折扣变化的时候会导致代码臃肿,难以维护。可以使用策略模式去解决这个问题。策略模式只适用管理一组同类型的算法,并且这些算法是完全互斥的情况。也就是说任何时候,多个策略中只有一个可以生效的那一种。

策略模式中出现的角色:

策略接口,Customer.java。

具体策略:CommonCustomer.java,SuperCustomer.java,VIPCustomer.java。

上下文类:Cashier.java。

策略接口,Customer.java,源代码如下所示:

import java.math.BigDecimal;
public interface Customer {
    /**
     * 计算折扣后的花费
     * @param oldCost 原花费
     * @return 折扣后的花费
     */
    public BigDecimal cost(BigDecimal oldCost);
}

具体策略:CommonCustomer.java,SuperCustomer.java,VIPCustomer.java。

import java.math.BigDecimal;
​
public class CommonCustomer implements Customer {
    @Override
    public BigDecimal cost(BigDecimal oldCost) {
        return oldCost.multiply(new BigDecimal(0.95));
    }
}
VIPCustomer.java:
​
package strategy;
​
import java.math.BigDecimal;
​
public class VIPCustomer implements Customer {
    @Override
    public BigDecimal cost(BigDecimal oldCost) {
        return oldCost.multiply(new BigDecimal(0.8));
    }
}
SuperCustomer.java :
​
package strategy;
​
import java.math.BigDecimal;
​
public class SuperCustomer implements Customer{
    @Override
    public BigDecimal cost(BigDecimal oldCost) {
        return oldCost.multiply(new BigDecimal(0.6));
    }
}

上下文类:Cashier.java。 测试代码如下所示:

public class Cashier {
private Customer customer;
​
private BigDecimal cost(BigDecimal oldCost) {
    return customer.cost(oldCost);
}
​
public Customer getCustomer() {
    return customer;
}
​
public void setCustomer(Customer customer) {
    this.customer = customer;
}
​
public static void main(String[] args) {
    Cashier cashier = new Cashier();
    CommonCustomer commonCustomer = new CommonCustomer();
    SuperCustomer superCustomer = new SuperCustomer();
    VIPCustomer vipCustomer = new VIPCustomer();
    BigDecimal bigDecimal = new BigDecimal(7.2);
    cashier.setCustomer(commonCustomer);
    System.out.println(cashier.cost(bigDecimal));
    cashier.setCustomer(vipCustomer);
    System.out.println(cashier.cost(bigDecimal));
    cashier.setCustomer(superCustomer);
    System.out.println(cashier.cost(bigDecimal));
}
}

运行截图如下所示:

image.png 策略模式的优点:

避免使用多重条件(if-else)语句。多重条件语句不易维护。

对“开闭原则”的完美支持,用户可以在不修改原有系统的基础上选择算法或行为,也可以灵活地增加新的算法或行为。

可以把公共的代码移到父类(策略类)里面,从而避免代码重复。

策略模式的缺点:

客户端必须知道所有的策略类,并自行决定使用哪一个策略类。这就意味着客户端必须理解这些算法的区别(调用的难度增加),以便适时选择恰当的算法类。这种策略类的创建及选择其实也可以通过工厂模式来辅助进行。

由于策略模式把每个具体的策略实现都单独封装成为类,如果备选的策略很多的话,那么对象的数目就会很可观(具体策略类的数量会很多)。可以通过使用享元模式在一定程度上减少对象的数量。