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

你可能感兴趣的文章
netty——Channl的常用方法、ChannelFuture、CloseFuture
查看>>
netty——Future和Promise的使用 线程间的通信
查看>>
Vue输出HTML
查看>>
netty——黏包半包的解决方案、滑动窗口的概念
查看>>
Netty中Http客户端、服务端的编解码器
查看>>
Netty中使用WebSocket实现服务端与客户端的长连接通信发送消息
查看>>
Netty中实现多客户端连接与通信-以实现聊天室群聊功能为例(附代码下载)
查看>>
Netty中的组件是怎么交互的?
查看>>
Netty中集成Protobuf实现Java对象数据传递
查看>>
netty之 定长数据流处理数据粘包问题
查看>>
Netty事件注册机制深入解析
查看>>
netty代理
查看>>
Netty入门使用
查看>>
netty入门,入门代码执行流程,netty主要组件的理解
查看>>
Netty原理分析及实战(一)-同步阻塞模型(BIO)
查看>>
Netty原理分析及实战(三)-高可用服务端搭建
查看>>
Netty原理分析及实战(二)-同步非阻塞模型(NIO)
查看>>
Netty原理分析及实战(四)-客户端与服务端双向通信
查看>>
Netty发送JSON格式字符串数据
查看>>
Netty和Tomcat的区别已经性能对比
查看>>