博客
关于我
[设计模式]策略模式(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操作时出现锁表
查看>>
MYSQL批量UPDATE的两种方式
查看>>
mysql批量修改字段名(列名)
查看>>
MySQL批量插入数据遇到错误1213的解决方法
查看>>
mysql技能梳理
查看>>
MySQL报Got an error reading communication packets错
查看>>
Mysql报错Can‘t create/write to file ‘/tmp/#sql_3a8_0.MYD‘ (Errcode: 28 - No space left on device)
查看>>
MySql报错Deadlock found when trying to get lock; try restarting transaction 的问题解决
查看>>
MySQL报错ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘
查看>>
Mysql报错Packet for query is too large问题解决
查看>>
mysql报错级别_更改MySQL日志错误级别记录非法登陆(Access denied)
查看>>
Mysql报错:too many connections
查看>>
MySQL报错:无法启动MySQL服务
查看>>
mysql授权用户,创建用户名密码,授权单个数据库,授权多个数据库
查看>>
mysql排序查询
查看>>
MySQL排序的艺术:你真的懂 Order By吗?
查看>>
MySQL排序的艺术:你真的懂 Order By吗?
查看>>
Mysql推荐书籍
查看>>
Mysql插入数据从指定选项中随机选择、插入时间从指定范围随机生成、Navicat使用存储过程模拟插入测试数据
查看>>
MYSQL搜索引擎
查看>>