[设计模式]策略模式(strategy)---算术运算
来源:互联网 发布:图文直播系统源码 编辑:程序博客网 时间:2024/05/16 19:15
策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类),提供辅助函数,关系图如下:
图中ICalculator提供统一的方法,
AbstractCalculator是辅助类,提供辅助方法,接下来,依次实现下每个类:
首先统一接口:
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 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 cal = new Plus(); int result = cal.calculate(exp); System.out.println(result); } }输出:10
策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。
1 0
- [设计模式]策略模式(strategy)---算术运算
- 设计模式----Strategy(策略)
- 设计模式--Strategy(策略)
- Strategy(策略)设计模式
- 设计模式----策略模式(Strategy)
- 设计模式--策略模式(Strategy)
- 设计模式C++(Strategy策略模式)
- 设计模式---策略模式(strategy)
- java 设计模式--策略模式(strategy)
- 【设计模式】之策略模式(Strategy)
- 设计模式之--策略模式(Strategy)
- 设计模式C++(Strategy策略模式)
- 设计模式(一)Strategy - 策略模式
- 设计模式之策略(strategy)模式
- 设计模式之策略模式(Strategy)
- 设计模式5--策略模式(Strategy)
- 设计模式-----策略模式(strategy)
- 浅学设计模式--策略(Strategy)模式
- QStringList用法总结
- Keepalive 基础概要及简单示例
- JavaSwing中itemStateChanged事件执行两次
- 目标检测的图像特征提取之(四)OpenCV中BLOB特征提取与几何形状分类
- Android--自定义控件(组合系统控件)
- [设计模式]策略模式(strategy)---算术运算
- 【BZOJ】4034 [HAOI2015]树上操作 树链剖分
- Angular-cli的安装(首先你一定要先安装node.js)
- JavaScript笔记
- SAP ODATA官网提供测试内容
- 自制linux系统
- msp430 launchpad 按键控制led亮灭
- Tiny4412上如何解决间断熄屏
- 5-14 周游世界(24分)