博客
关于我
[设计模式]策略模式(strategy)---算术运算
阅读量:531 次
发布时间: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/

你可能感兴趣的文章
腾讯Java面试题,从基础到源码统统帮你搞定,2年以上经验必看
查看>>
字节跳动算法工程师总结:腾讯+字节+阿里面经真题汇总,含面试题+答案
查看>>
LeetCode 22. 括号生成
查看>>
(二)MyBatis学习笔记——使用映射配置文件进行CRUD、核心配置文件使用
查看>>
LeetCode 76. 最小覆盖子串
查看>>
架构 -- rsync补充02
查看>>
shell基础 - 03
查看>>
第七课时logback日志框架介绍及应用
查看>>
第十一课时通讯录列表前后端调用
查看>>
java注解完整实例
查看>>
6.4 jmeter基础知识--变量
查看>>
6.6 jmeter基础—系统日志
查看>>
10 测试脚本结果分析
查看>>
先验概率,后验概率,似然函数,贝叶斯公式
查看>>
python初学者容易犯的错误
查看>>
github资源下载assets中的各种格式
查看>>
ubuntu中添加截图和录屏快捷键
查看>>
基于libVLC的视频播放器之四:直接使用libVLC
查看>>
Qt5下OpenGL程序的新写法
查看>>
FFmpeg:‘UINT64_C‘ was not declared in ths scope
查看>>