策略模式(Strategy)-----基于JAVA语言
来源:互联网 发布:淘宝价格旁已验证正品 编辑:程序博客网 时间:2024/06/05 05:29
策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,也可以设计一个抽象类(可有可无,属于辅助类),提供辅助函数
例子:
策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。
我们之前在TreeSet排序的时候,有一种叫做资客户化排序的方式,就是给TreeSet传一个比较器对象,这个其实就是使用了策略模式
例子:
//统一的接口 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 { public int calculate(String exp) { int arrayInt[] = split(exp,"[+]"); return arrayInt[0]+arrayInt[1]; } } 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 Test { public static void main(String[] args) { String exp = "2+8"; ICalculator cal = new Plus(); int result = cal.calculate(exp); System.out.println(result); } }
策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。
我们之前在TreeSet排序的时候,有一种叫做资客户化排序的方式,就是给TreeSet传一个比较器对象,这个其实就是使用了策略模式
阅读全文
0 0
- 策略模式(Strategy)-----基于JAVA语言
- java 策略(Strategy)模式
- Java策略模式(Strategy)
- Java策略模式(Strategy)
- Java模式 - 策略模式(Strategy)
- java 设计模式--策略模式(strategy)
- Java设计模式----策略模式(Strategy)
- Java策略模式(Strategy模式)
- java(15)-策略模式(Strategy Pattern)
- JAVA设计模式---策略(strategy)
- Java策略模式(Strategy模式)
- 策略(Strategy)模式
- Strategy(策略)模式
- 策略(Strategy)模式
- Strategy(策略模式)
- 策略模式(Strategy)
- 策略模式(Strategy)
- Strategy(策略模式)
- 让用户对产品上瘾,需要这4个环节
- ssm 中 ajax json
- Axure玩得不好?别怕!6周让你的Axure水平达到腾讯产品招聘要求
- ubuntu16.04 安装caffe 无GPU
- C++中break和continue的区别及注意事项
- 策略模式(Strategy)-----基于JAVA语言
- HBase shell scan 模糊查询
- 读书笔记:《设计模式解析》
- 关于手机已经设置成开发者模式但是Android studio不能识别问题
- final, finally, finalize 的区别
- 新零售的新思路:如何管理复杂?
- SpringCloud分布式开发五大神兽(一)
- Go语言开发环境搭建
- 观宋宝华设备树视频的感想