博客
关于我
[设计模式]策略模式(strategy)---算术运算
阅读量:546 次
发布时间:2019-03-09

本文共 1593 字,大约阅读时间需要 5 分钟。

策略模式是一种软件设计模式,旨在将算法和其配置管理,使其易于交换和扩展。通过定义统一的接口,系统可以在运行时动态指定哪种算法执行,从而实现灵活性和扩展性。

本文将设计一个接口,并提供相应的实现类,逐步讲解策略模式的应用。

接口定义

public interface ICalculator {    public int calculate(String exp);}

辅助类

public abstract class AbstractCalculator {    public int[] split(String exp, String opt) {        String[] array = exp.split(opt);        int[] arrayInt = new int[2];        arrayInt[0] = Integer.parseInt(array[0]);        arrayInt[1] = Integer.parseInt(array[1]);        return arrayInt;    }}

实现类

public class Plus extends AbstractCalculator implements ICalculator {    @Override    public int calculate(String exp) {        int[] arrayInt = split(exp, "\\+");        return arrayInt[0] + arrayInt[1];    }}
public class Minus extends AbstractCalculator implements ICalculator {    @Override    public int calculate(String exp) {        int[] arrayInt = split(exp, "-");        return arrayInt[0] - arrayInt[1];    }}
public class Multiply extends AbstractCalendar extends AbstractCalculator implements ICalculator {    @Override    public int calculate(String exp) {        int[] arrayInt = split(exp, "\\*");        return arrayInt[0] * arrayInt[1];    }}

测试案例

public class StrategyTest {    public static void main(String[] args) {        String exp = "2+8";        ICalculator calculator = new Plus();        int result = calculator.calculate(exp);        System.out.println(result);    }}

输出结果

输出结果为:10

策略模式的优势

策略模式通过封装算法实现了良好的扩展性和可维护性。新增或删除算法实现只需添加或移除相应的策略实现即可,无需修改客户端代码。这种模式非常适合算法决策系统,允许用户自由选择所需的算法。

通过规范化接口定义,系统可以动态加载不同算法实现,减少硬编码耦合度。这种灵活性和可配置性是策略模式的一大亮点。

通过上述设计,用户可以根据需要选择最佳的算法实现,实现高度的灵活性和可扩展性。

转载地址:http://jweiz.baihongyu.com/

你可能感兴趣的文章