Java设计模式之策略模式
来源:互联网 发布:马小丝的淘宝店 编辑:程序博客网 时间:2024/06/05 09:46
策略模式(strategy)
概念:
定义一组算法,并把其封装到一个对象中。然后在运行时,可以灵活的使用其中的一个算法。
适用:
1.多个类只区别在表现行为不同,可以使用Strategy模式,在运行时动态选择具体要执行的行为。
2.需要在不同情况下使用不同的策略(算法),或者策略还可能在未来用其它方式来实现。
3.对客户隐藏具体策略(算法)的实现细节,彼此完全独立。
代码示例:
/** * 所有策略的抽象接口 * 提供计算方法的接口 */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 Minus extends AbstractCalculator implements ICalculator { public int calculate(String exp) { int arrayInt[] = split(exp,"-"); return arrayInt[0]-arrayInt[1]; } }
/** * 具体的策略实现 * 相乘计算 */public class Multiply extends AbstractCalculator implements ICalculator { public int calculate(String exp) { int arrayInt[] = split(exp,"\\*"); return arrayInt[0]*arrayInt[1]; } }
/** * 具体的策略实现 * 相加计算 */public class Plus extends AbstractCalculator implements ICalculator { public int calculate(String exp) { int arrayInt[] = split(exp,"\\+"); return arrayInt[0]+arrayInt[1]; } }
/** * 策略模式的测试 * 根据不同的策略执行不同的动作 */public class Test { public static void main(String[] args) { String exp = "2+8"; ICalculator cal = new Plus(); // 相加策略 int result = cal.calculate(exp); System.out.println(result); } }
阅读全文
0 0
- Java设计模式之策略设计模式
- Java设计模式之策略设计模式
- Java设计模式之策略
- Java设计模式之策略模式
- java设计模式之 策略模式
- JAVA 设计模式之 策略模式
- java设计模式之策略模式 Strategy
- java设计模式之策略模式
- java设计模式之策略模式
- 浅谈Java设计模式之---策略模式
- java设计模式之策略模式
- Java设计模式之策略模式
- java设计模式之策略模式
- Java设计模式之策略模式
- Java设计模式之策略模式
- java设计模式之策略模式
- 设计模式之策略模式(java)
- Java设计模式笔记之策略模式
- 7.动态sql
- 数据库专题讲解/持续更新中
- SpringBoot整合shiro框架
- Standard 1.1.x VM与Standard VM的区别
- mysql xtrabackup备份恢复单表
- Java设计模式之策略模式
- 读java编程建议--笔记三
- 11_Workoutlogger ---ReactJS and Flux: Learn By Building 10 Projects
- 练习5
- eclipse报错"错误: 找不到或无法加载主类 jdk1.7"解决方案
- c语言中的指针
- Redis快速入门
- java只安装了jre,没有安装jdk,是不能运行源代码
- Ubuntu 16.04 桌面壁纸问题解决