设计模式-策略模式

目录

1.初步认识

2.角色功能

3.代码实现

4.优缺点

1.初步认识

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

2.角色功能

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

3.代码实现

实体类

java 复制代码
/**
 * 实体类
 */
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;
    }
}

抽象类

java 复制代码
/**
 * 抽象类
 */
public abstract class Strategy {

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

上下文

java 复制代码
/**
 * @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);
    }
}

具体的策略

java 复制代码
/**
 * @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.优缺点

  • 优点:
    • 满足开闭原则,当增加新的具体策略时,不需要修改上下文类的代码,上下文就可以引用新的具体策略的实例
    • 避免使用多重条件判断,如果不用策略模式可能会使用多重条件语句不利于维护,和工厂模式的搭配使用
  • 缺点:
    • 策略类数量会增多,每个策略都是一个类,复用的可能性很小
    • 对外暴露了类所有的行为和算法,行为过多导致策略类膨胀
相关推荐
Dizzy.5174 分钟前
数据结构(查找)
数据结构·学习·算法
软件开发技术局26 分钟前
撕碎QT面具(8):对控件采用自动增加函数(转到槽)的方式,发现函数不能被调用的解决方案
开发语言·qt
周杰伦fans2 小时前
C#中修饰符
开发语言·c#
yngsqq2 小时前
c# —— StringBuilder 类
java·开发语言
赔罪2 小时前
Python 高级特性-切片
开发语言·python
Asthenia04122 小时前
浏览器缓存机制深度解析:电商场景下的性能优化实践
后端
星星点点洲2 小时前
【操作幂等和数据一致性】保障业务在MySQL和COS对象存储的一致
java·mysql
xiaolingting3 小时前
JVM层面的JAVA类和实例(Klass-OOP)
java·jvm·oop·klass·instanceklass·class对象
分别努力读书3 小时前
acm培训 part 7
算法·图论
武乐乐~3 小时前
欢乐力扣:赎金信
算法·leetcode·职场和发展