设计模式13-策略模式
来源:互联网 发布:歼十模型淘宝 编辑:程序博客网 时间:2024/06/15 21:15
简介
行为模式:
策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。
实例
统一接口
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); } }
备注
策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。
其他设计模式http://blog.csdn.net/qq_23370223/article/category/7193147
阅读全文
1 0
- 设计模式13-策略模式
- 设计模式-策略模式
- 设计模式:策略模式
- 设计模式-策略模式
- 设计模式 - 策略模式
- 设计模式-策略模式
- 设计模式-----策略模式
- 设计模式 策略模式
- 设计模式-策略模式
- 设计模式-【策略模式】
- 设计模式-----策略模式
- 设计模式-策略模式
- 设计模式--策略模式
- 设计模式- 策略模式
- 设计模式- 策略模式
- 设计模式------策略模式
- 设计模式--策略模式
- 设计模式-策略模式
- Python(5) 面向对象相关
- impdp或expdp报错ORA-39002: invalid operation,ORA-39070: Unable to open the log file
- Python(6) 异常处理
- two_sum
- 快速掌握Glide图片加载的强大功能你如果
- 设计模式13-策略模式
- c++设计模式三,工厂模式
- 洛谷 P1220 关路灯
- csdn 的友链设置
- Python(7) 日期操作
- 图文讲解jQuery动画特效
- Spring Aop(二)——基于Aspectj注解的Aop简单实现
- 在Eclipse中发布项目
- 【C语言·字符串】关于字符串的存储问题