博客
关于我
[设计模式]策略模式(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/

你可能感兴趣的文章
mysql中出现update-alternatives: 错误: 候选项路径 /etc/mysql/mysql.cnf 不存在 dpkg: 处理软件包 mysql-server-8.0的解决方法(全)
查看>>
Mysql中各类锁的机制图文详细解析(全)
查看>>
MySQL中地理位置数据扩展geometry的使用心得
查看>>
Mysql中存储引擎简介、修改、查询、选择
查看>>
Mysql中存储过程、存储函数、自定义函数、变量、流程控制语句、光标/游标、定义条件和处理程序的使用示例
查看>>
mysql中实现rownum,对结果进行排序
查看>>
mysql中对于数据库的基本操作
查看>>
Mysql中常用函数的使用示例
查看>>
MySql中怎样使用case-when实现判断查询结果返回
查看>>
Mysql中怎样使用update更新某列的数据减去指定值
查看>>
Mysql中怎样设置指定ip远程访问连接
查看>>
mysql中数据表的基本操作很难嘛,由这个实验来带你从头走一遍
查看>>
Mysql中文乱码问题完美解决方案
查看>>
mysql中的 +号 和 CONCAT(str1,str2,...)
查看>>
Mysql中的 IFNULL 函数的详解
查看>>
mysql中的collate关键字是什么意思?
查看>>
MySql中的concat()相关函数
查看>>
mysql中的concat函数,concat_ws函数,concat_group函数之间的区别
查看>>
MySQL中的count函数
查看>>
MySQL中的DB、DBMS、SQL
查看>>