设计模式(二十一)行为型模式---策略模式(strategy)

策略模式简介

策略模式(strategy pattern)是定义一些算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化,不会影响使用算法的客户。

结构

  • 1.抽象策略类角色(Abstract Strategy):抽象策略角色一般是接口或者抽象类,定义出具体策略角色所需要的接口。
  • 2.具体策略类角色(Concrete Strategy):实现了抽象策略定义的接口,提供具体的算法实现。
  • 3.环境角色(Context):持有一个策略类的引用,最终给客户端使用。

UML图

在这里插入图片描述

具体实现

例子:商场推出了三种促销活动,买一送一,满1000换购,满30-30,使用策略模式达到随时跟换促销活动场景。

UML图

在这里插入图片描述

代码实现

  • 抽象策略角色
package com.xxliao.pattern.behavioral.strategy.demo;

/**
 * @author xxliao
 * @description:  抽象策略接口 -促销活动
 * @date 2024/5/27 17:07
 */
public interface Strategy {

    void show();
}
  • 具体策略角色
package com.xxliao.pattern.behavioral.strategy.demo;

/**
 * @author xxliao
 * @description: 具体策略类 - 买一送一
 * @date 2024/5/27 17:08
 */
public class StrategyOne implements Strategy{

    @Override
    public void show() {
        System.out.println("买一送一。。。");
    }
}
package com.xxliao.pattern.behavioral.strategy.demo;

/**
 * @author xxliao
 * @description: 具体策略类 - 满300 - 30
 * @date 2024/5/27 17:09
 */
public class StrategyTwo implements Strategy{

    @Override
    public void show() {
        System.out.println("满300 - 30");
    }
}
package com.xxliao.pattern.behavioral.strategy.demo;

/**
 * @author xxliao
 * @description: 具体策略类 -满1000 可换购200以内的任意商品
 * @date 2024/5/27 17:10
 */
public class StrategyThree implements Strategy {

    @Override
    public void show() {
        System.out.println("满1000 可换购200以内的任意商品");
    }
}
  • 环境角色(上下文)
package com.xxliao.pattern.behavioral.strategy.demo;

/**
 * @author xxliao
 * @description: 环境角色
 * @date 2024/5/27 17:11
 */

public class Context {

    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void sale() {
        this.strategy.show();
    }
}
  • 测试客户端
package com.xxliao.pattern.behavioral.strategy.demo;

/**
 * @author xxliao
 * @description: 策略模式 测试客户端
 * @date 2024/5/27 17:12
 */
public class Client {

    public static void main(String[] args) {
        //
        Context context = new Context(new StrategyOne());
        context.sale();
    }
}
  • 测试结果
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骑车上酒吧

帮到了您,有闲钱,再打赏哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值