设计模式之策略模式(常规版&Lambda Function版)

目录

前言

UML类图

Demo代码

利用业务场景理解策略模式的使用场景

如上应用场景例子引出策略模式的具体应用

Lambda Function实现策略模式

Demo Code1

Demo Code2

策略模式的优缺点

优点

缺点


前言

        策略,指的是可以实现目标的方案集合,在某些特定情况下,策略之间是可以相互替换的。

        比如在外卖平台上的这些优惠。满减、会员和红包等,每一个大项优惠都具体包含了多个优惠方案。如满减活动中,可以同时有满28减18、满58减38等。会员包含普通会员、超级会员等。

        每一个优惠方式下面的多个优惠方案,其实都是一个策略。这些策略之间是相互排斥、可替换的。并且是有一定的优先级顺序的。

        在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。

策略模式 | 菜鸟教程

UML类图

        我们将创建一个定义活动的 Strategy 接口和实现了 Strategy 接口的实体策略类。Context 是一个使用了某种策略的类。StrategyPatternDemo,我们的演示类使用 Context 和策略对象来演示 Context 在它所配置或使用的策略改变时的行为变化。

Demo代码

GOF23/StrategyMain.java at master · liuchaoOvO/GOF23 · GitHub

利用业务场景理解策略模式的使用场景

        拿点外卖中会员折扣活动举例子来说,平台商家为了促销,设置多种会员优惠,包含超级会员8折、普通会员9折和普通用户没有折扣三种。用户在付款的时候,平台根据用户的会员等级,就可以知道用户符合哪种折扣策略,进而计算出应付金额。

代码中如下:

public BigDecimal calPrice(BigDecimal orderPrice, String buyerType) {
    if (BuyerType.SVIP.name.equals(buyerType)) {
        return orderPrice.multiply(new BigDecimal(0.8));
    }
    if (BuyerType.VIP.name.equals(buyerType)) {
        return orderPrice.multiply(new BigDecimal(0.9));
    }
    return orderPrice;
}

        代码比较简单,就是在代码中通过if-else进行逻辑判断,不同类型的会员享受不同的折扣价。此时,平台增加了一种店铺专属会员,这种会员可以专享某一个店铺菜品的7折优惠。

代码需要改成如下:

public BigDecimal calPrice(BigDecimal orderPrice, String buyerType) {
    if (BuyerType.EXCLUSIVE_VIP.name.equals(buyerType)) {
        return orderPrice.multiply(new BigDecimal(0.7));
    }
    if (BuyerType.SVIP.name.equals(buyerType)) {
        return orderPrice.multiply(new BigDecimal(0.8));
    }
    if (BuyerType.VIP.name.equals(buyerType)) {
        return orderPrice.multiply(new BigDecimal(0.9));
    }
    return orderPrice;
}

        而以后,随着业务发展,新的需求要求专属会员要在店铺下单金额大于28元的时候才可以享受优惠。

代码就需要再次修改:

public BigDecimal calPrice(BigDecimal orderPrice, String buyerType) {
    if (BuyerType.EXCLUSIVE_VIP.name.equals(buyerType)) {
        if(orderPrice.compareTo(new BigDecimal(28))>0){
            return orderPrice.multiply(new BigDecimal(0.7));
        }
    }
    if (BuyerType.SVIP.name.equals(buyerType)) {
        return orderPrice.multiply(new BigDecimal(0.8));
    }
    if (BuyerType.VIP.name.equals(buyerType)) {
        return orderPrice.multiply(new BigDecimal(0.9));
    }
    return orderPrice;
}

        接着后来又有一个复杂的需求,如果用户的会员已经到期了,并且到期时间在一周内,那么就对用户的单笔订单按照超级会员进行折扣,并在收银台进行强提醒,引导用户再次开通会员,而且折扣只进行一次。

代码需要做如下修改:

public BigDecimal calPrice(BigDecimal orderPrice, String buyerType) {
    if (BuyerType.EXCLUSIVE_VIP.name.equals(buyerType)) {
        if (orderPrice.compareTo(new BigDecimal(28)) > 0) {
            return orderPrice.multiply(new BigDecimal(0.7));
        }
    }
    if (BuyerType.SVIP.name.equals(buyerType)) {
        return orderPrice.multiply(new BigDecimal(0.8));
    }
    if (BuyerType.VIP.name.equals(buyerType)) {
        //过期天数
        int vipExpireDays = getVipExpireDays();
        //过期使用次数为0
        int vipTime = getVipTime();
        if (vipExpireDays < 7 && vipTime == 0) {
            //更新过期使用次数
            updatevipExpireUsed();
            return orderPrice.multiply(new BigDecimal(0.8));
        }
        return orderPrice.multiply(new BigDecimal(0.9));
    }
    return orderPrice;
}

如上应用场景例子引出策略模式的具体应用

        以上代码,所有关于会员折扣的代码全部都写在了一个方法中,增加或者减少一种会员类型,就需要改动到整个方法。还要考虑这种会员折扣的优先级问题。除了增加会员类型外,其中任何一种会员类型的折扣策略发生变化,也需要改动到整个算法。这就会导致这个算法越来越臃肿,进而得到的后果就是代码行数越来越多,开发人员改动一点点代码都需要把所有功能全部都回归一遍。就比如说只是把超级会员的折扣从8折改为8.5折,这时候因为代码都在一起,那就需要在上线的时候对于会员折扣的所有功能进行回归。久而久之,代码可读性、可维护性、可扩展性均变得极低,并且回归成本较高。

1️⃣策略模式

        日常生活中,要实现目标,有很多方案,每一个方案都被称之为一个策略。在软件开发中也常常遇到类似的情况,实现某一个功能有多个途径,此时可以使用一种设计模式来使得系统可以灵活地选择解决途径,也能够方便地增加新的解决途径。这就是策略模式。

策略模式,指的是定义一系列算法,将每一个算法封装起来,并让它们可以相互替换。策略模式让算法独立于使用它的客户而变化。

        特别说明一下,策略模式只适用管理一组同类型的算法,并且这些算法是完全互斥的情况。也就是说任何时候,多个策略中只有一个可以生效的那一种。如满减中的满28减18与满58减38之间;普通会员折扣与超级会员折扣之间等。

        在策略模式中,定义一些独立的类来封装不同的算法,每一个类封装一个具体的算法,在这里,每一个封装算法的类都可以称之为策略,为了保证这些策略的一致性,一般会用一个抽象的策略类来做算法的定义,而具体每种算法则对应于一个具体策略类。

        要实现策略模式,肯定离不开策略。如前面提到的超级会员、普通会员、专属会员等的折扣其实都是策略。完全可以通过策略模式来实现。

实现策略模式主要包含的角色如下:

2️⃣抽象策略类

        先定义一个接口,这个接口就是抽象策略类,该接口定义了计算价格方法,具体实现方式由具体的策略类来定义。

public interface Buyer {
    BigDecimal calPrice(BigDecimal orderPrice);
}

3️⃣具体策略类

针对不同的会员,定义三种具体的策略类,每个类中都分别实现计算价格方法。

public class ExclusiveVIP implements Buyer {
    @Override
    public BigDecimal calPrice(BigDecimal orderPrice) {
        if (orderPrice.compareTo(new BigDecimal(28)) > 0) {
            return orderPrice.multiply(new BigDecimal(0.7));
        }
        return orderPrice;
    }
}
public class SVIP implements Buyer {
    @Override
    public BigDecimal calPrice(BigDecimal orderPrice) {
        return orderPrice.multiply(new BigDecimal(0.8));
    }
}
public class VIP implements Buyer {
    @Override
    public BigDecimal calPrice(BigDecimal orderPrice) {
        //过期天数
        int vipExpireDays = getVipExpireDays();
        //过期使用次数为0
        int vipTime = getVipTime();
        if (vipExpireDays < 7 && vipTime == 0) {
            //更新过期使用次数
            updatevipExpireUsed();
            return orderPrice.multiply(new BigDecimal(0.8));
        }
        return orderPrice.multiply(new BigDecimal(0.9));
    }
}

        上面几个类的定义体现了封装变化的设计原则,不同会员的具体折扣方式改变不会影响到其他的会员。

4️⃣上下文类

        定义好了抽象策略类和具体策略类之后,再来定义上下文类,所谓上下文类,就是集成算法的类。这个例子中就是收银台系统。采用组合的方式把会员集成进来。

public class Cashier {
    private Buyer buyer;
    public Cashier(Buyer buyer) {
        this.buyer = buyer;
    }
    public BigDecimal qupta(BigDecimal orderPrice) {
        return this.buyer.calPrice(orderPrice);
    }
}

        这个 Cashier 类就是一个上下文类,该类的定义体现了多用组合,少用继承。针对接口,不针对实现两个设计原则

        由于这里采用了组合+接口的方式,后面再推出其他类型会员的时候无须修改 Cashier 类。只要再定义一个类实现 Buyer 接口就可以了。

        除了增加会员类型以外,想要修改某个会员的折扣情况的时候,只需要修改该会员对应的策略类就可以了,不需要修改到其他的策略。也就控制了变更的范围。大大降低了成本。

5️⃣测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.math.BigDecimal;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DemoApplication.class})
public class TradeTest {
    @Test
    public void testCash() {

        Cashier ex = new Cashier(new ExclusiveVIP());
        System.out.println(ex.quota(new BigDecimal(100)));

        Cashier svip = new Cashier(new SVIP());
        System.out.println(svip.quota(new BigDecimal(100)));

        Cashier vip = new Cashier(new VIP());
        System.out.println(vip.quota(new BigDecimal(100)));
    }
}

        由示例可知,策略模式仅仅封装算法,提供新的算法插入到已有系统中,策略模式并不决定在何时使用何种算法。在什么情况下使用什么算法是由客户端决定的。

Lambda Function实现策略模式

        策略模式+Map+Function组合,定义一个Map来做策略分发,通过Map的key进行逻辑决策,根据key找到value之后通过Function执行返回结果。

优点:这样不仅保证策略类不会太多,而且可以简单的获得全量的策略视图。

Demo Code1

public class StrategyTest1 {
    private static Map<String, Function<String,String>> resultDispatcherMuti = new HashMap<>();

    static {
        resultDispatcherMuti.put("校验1",order->String.format("对%s执行业务逻辑1", order));
        resultDispatcherMuti.put("校验2",order->String.format("对%s执行业务逻辑2", order));
        resultDispatcherMuti.put("校验3",order->String.format("对%s执行业务逻辑3", order));
        resultDispatcherMuti.put("校验4",order->String.format("对%s执行业务逻辑4", order));
    }

    public static String getResultDispatcher(String order) {
        Function<String, String> result = resultDispatcherMuti.get(order);
        if (result!=null) {
           return result.apply(order);
        }
        return "不在处理的业务中返回逻辑错误";
    }

    public static void main(String[] args) {
        String result = getResultDispatcher("校验1");
        System.out.println(result);
    }       
}

我们定义了一个Map<String, Function<String,String>>,值的类型是Function<T,R>

/**
 * Represents a function that accepts one argument and produces a result.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #apply(Object)}.
 *
 * @param <T> the type of the input to the function
 * @param <R> the type of the result of the function
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

}

这个接口是用@FunctionalInterface标注的,代表它是一个函数式接口。

看类注释的话,简单翻译一下,就是这个接口接受一个参数,然后返回一个结果回去,这是一个函数。

看接口的泛型,T代表入参类型,R代表返回值类型。

我们看一下这个apply方法的使用,方法注释的意思是将函数应用到给定的参数上,t是入参,返回R类型的值。

我们看一下我们策略模式中Map的初始化方法:

private static Map<String, Function<String,String>> resultDispatcherMuti = new HashMap<>();

static {
   resultDispatcherMuti.put("校验1",order->String.format("对%s执行业务逻辑1", order));
}

order->String.format("对%s执行业务逻辑1", order)这个就是lambda写法,还原成我们熟悉的写法大概就是下面这样:

public String getResult(String order) {
    return  String.format("对%s执行业务逻辑1", order);
 }

lambda相当于给我们生成了一个匿名方法。

查看一下编译之后的class文件,如下所示:

对代码进行debug的话,会发现在内存中生成了一个带lambda后缀的类,这是Function的实现类,看一下编译的class 文件路径,发现没StrategyTest1  lambda,说明这个类存在于内存中。

Demo Code2

@Component
public class DemoConfig {

    private final DataSourceTenantManager dataSourceTenantManager;
    private final DataCenterMapper dataCenterMapper;
    @Autowired
    public DemoConfig(
            DataSourceTenantManager dataSourceTenantManager,
            DataCenterMapper dataCenterMapper
    ) {
        this.dataSourceTenantManager = dataSourceTenantManager;
        this.dataCenterMapper = dataCenterMapper;
    }

    @PostConstruct
    public void init() {
        List<DataCenter> dataCenterList = dataCenterMapper.selectList(new EntityWrapper<>());
        Map<String, DataCenter> dataCenterMap = dataCenterList.stream().collect(Collectors.toMap(DataCenter::generateTenantId, Function.identity()));
        dataSourceTenantManager.setTenantResolver(tenantId -> resolveDataSourceConfig(dataCenterMap.get(tenantId)));
    }

    private DynamicDataSourceConfig.DataSourceConfigGroup resolveDataSourceConfig(DataCenter dataCenter) {
        return JSON.parseObject(dataCenter.getDbConfig(), DynamicDataSourceConfig.DataSourceConfigGroup.class);
    }
}

@Configuration
public class DataSourceTenantManager  {
    private final Logger log = LoggerFactory.getLogger(DataSourceTenantManager.class);
    private Function<String, DataSourceConfigGroup> tenantResolver;

    public void setTenantResolver(Function<String, DataSourceConfigGroup> tenantResolver) {
        this.tenantResolver = tenantResolver;
    }
 //下面就可以利用tenantResolver.apply(tenantId) 使用 tenantResolver

    public void testBussinessMethod(String tenantId) {
   DataSourceConfigGroup dataSourceConfigGroup= tenantResolver.apply(tenantId); //策略模式的一种实现: 通过传入不同的tenantId值 获取不同的dataSourceConfigGroup配置
  other bussiness code...
}
}

策略模式的优缺点

策略模式可以充分的体现面向对象设计原则中的封装变化、多用组合,少用继承、针对接口编程,不针对实现编程等原则。

优点

1️⃣策略模式的关注点不是如何实现算法,而是如何组织、调用这些算法,从而让程序结构更灵活,具有更好的维护性和扩展性。
2️⃣策略模式中各个策略算法是平等的。对于一系列具体的策略算法,地位是完全一样的。正因为这个平等性,才能实现算法之间可以相互替换。所有的策略算法在实现上也是相互独立的,相互之间是没有依赖的。所以可以这样描述这一系列策略算法:策略算法是相同行为的不同实现。
3️⃣运行期间,策略模式在每一个时刻只能使用一个具体的策略实现对象,虽然可以动态地在不同的策略实现中切换,但是同时只能使用一个。

如果所有的具体策略类都有一些公有的行为。这时候,就应当把这些公有的行为放到共同的抽象策略角色 Strategy 类里面。当然这时候抽象策略角色必须要用 Java 抽象类实现,而不能使用接口。但是,编程中没有银弹,策略模式也不例外,也有一些缺点,先来回顾总结下优点:

1️⃣策略模式提供了对“开闭原则”的完美支持,用户可以在不修改原有系统的基础上选择算法或行为,也可以灵活地增加新的算法或行为。
2️⃣策略模式提供了管理相关的算法族的办法。策略类的等级结构定义了一个算法或行为族。恰当使用继承可以把公共的代码移到父类里面,从而避免代码重复。
3️⃣使用策略模式可以避免使用多重条件(if-else)语句。多重条件语句不易维护,它把采取哪一种算法或采取哪一种行为的逻辑与算法或行为的逻辑混合在一起,统统列在一个多重条件语句里面,比使用继承的办法还要原始和落后。

缺点

1️⃣客户端必须知道所有的策略类,并自行决定使用哪一个策略类。这就意味着客户端必须理解这些算法的区别,以便适时选择恰当的算法类。这种策略类的创建及选择其实也可以通过工厂模式来辅助进行。
2️⃣由于策略模式把每个具体的策略实现都单独封装成为类,如果备选的策略很多的话,那么对象的数目就会很可观。可以通过使用享元模式在一定程度上减少对象的数量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值