什么叫策略模式,举个例子

  1. 首先,我们定义一个接口:
public interface CalculationStrategy {
    int calculate(int a, int b);
}
  1. 然后,我们为每种运算创建一个类:
public class AddStrategy implements CalculationStrategy {
    public int calculate(int a, int b) {
        return a + b;
    }
}

public class SubtractStrategy implements CalculationStrategy {
    public int calculate(int a, int b) {
        return a - b;
    }
}

public class MultiplyStrategy implements CalculationStrategy {
    public int calculate(int a, int b) {
        return a * b;
    }
}

public class DivideStrategy implements CalculationStrategy {
    public int calculate(int a, int b) {
        if (b != 0) {
            return a / b;
        }
        throw new ArithmeticException("Cannot divide by zero");
    }
}
  1. 最后,我们创建一个计算器类来使用这些策略:
public class Calculator {
    private CalculationStrategy strategy;

    public void setStrategy(CalculationStrategy strategy) {
        this.strategy = strategy;
    }

    public int executeStrategy(int a, int b) {
        return strategy.calculate(a, b);
    }
}
  1. 使用这个计算器:
Calculator calc = new Calculator();

// 执行加法
calc.setStrategy(new AddStrategy());
System.out.println("10 + 5 = " + calc.executeStrategy(10, 5));

// 执行减法
calc.setStrategy(new SubtractStrategy());
System.out.println("10 - 5 = " + calc.executeStrategy(10, 5));

在这个例子中:

  • CalculationStrategy 是策略接口
  • AddStrategy, SubtractStrategy 等是具体的策略实现
  • Calculator 是使用策略的类

策略模式的好处是:

  1. 如果我们想要添加新的运算(比如求幂),我们只需要创建一个新的策略类,而不需要修改已有的代码。
  2. 我们可以在运行时改变计算器的行为,而不需要使用复杂的条件语句。

这就是策略模式的核心思想:将算法(在这个例子中是不同的计算方法)封装到独立的类中,使它们可以互相替换。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值