设计模式-策略模式

目录

1.初步认识

2.角色功能

3.代码实现 

4.优缺点

1.初步认识

  • 策略模式(Strategy Pattern):定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换

2.角色功能

  • Context上下文:屏蔽高层模块对策略、算法的直接访问,封装可能存在的变化
  • Strategy策略角色:抽象策略角色,是对策略、算法家族的抽象,定义每个策略或算法必须具有的方法和属性
  • ConcreteStrategy具体策略角色:用于实现抽象策略中的操作,即实现具体的算法 

3.代码实现 

实体类

/**
 * 实体类
 */
public class Order {

    private double price;
    private int userId;
    private int productId;

    public Order() {
    }

    public Order(double price, int userId, int productId) {
        this.price = price;
        this.userId = userId;
        this.productId = productId;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

抽象类

/**
 * 抽象类
 */
public abstract class Strategy {

    //计算价格抽象方法,计算折扣价格
    public abstract double computePrice(Order order);
}

上下文

/**
 * @className: PromotionContext
 * @author: 会敲代码的小张
 * @date: 2024/9/10 11:55
 * @Version: 1.0
 * @description: 策略上下文
 */
public class PromotionContext {

    private Strategy strategy;

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

    /**
     * 根据策略计算最终价格
     * @param order
     * @return
     */
    public double execute(Order order){
        return strategy.computePrice(order);
    }
}

具体的策略

/**
 * @className: NormalActivity
 * @author: 会敲代码的小张
 * @date: 2024/9/10 11:57
 * @Version: 1.0
 * @description: 具体的策略-1-正常价格
 */
public class NormalActivity extends Strategy{


    @Override
    public double computePrice(Order order) {
        return order.getPrice();
    }
}


/**
 * @className: DisCountActivity
 * @author: 会敲代码的小张
 * @date: 2024/9/10 11:58
 * @Version: 1.0
 * @description: 具体策略-2-打折价格
 */
public class DisCountActivity extends Strategy {

    //具体折扣
    private double rate;

    public DisCountActivity(double rate) {
        this.rate = rate;
    }

    @Override
    public double computePrice(Order order) {
        return order.getPrice() * rate;
    }
}

4.优缺点

  • 优点:
    • 满足开闭原则,当增加新的具体策略时,不需要修改上下文类的代码,上下文就可以引用新的具体策略的实例
    • 避免使用多重条件判断,如果不用策略模式可能会使用多重条件语句不利于维护,和工厂模式的搭配使用
  • 缺点:
    • 策略类数量会增多,每个策略都是一个类,复用的可能性很小
    • 对外暴露了类所有的行为和算法,行为过多导致策略类膨胀
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

会敲代码的小张

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值