13、策略模式(strategy)
来源:互联网 发布:淘宝官方自营店是什么 编辑:程序博客网 时间:2024/06/07 06:11
13、策略模式(strategy)
策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类),提供辅助函数,关系图如下:
图中ICalculator提供同意的方法,
AbstractCalculator是辅助类,提供辅助方法,接下来,依次实现下每个类:
首先统一接口:
1
2
3
public
interface
ICalculator {
public
int
calculate(String exp);
}
辅助类:
1
2
3
4
5
6
7
8
9
10
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;
}
}
三个实现类:
1
2
3
4
5
6
7
8
public
class
Plus
extends
AbstractCalculator
implements
ICalculator {
@Override
public
int
calculate(String exp) {
int
arrayInt[] = split(exp,
"\\+"
);
return
arrayInt[
0
]+arrayInt[
1
];
}
}
1
2
3
4
5
6
7
8
9
public
class
Minus
extends
AbstractCalculator
implements
ICalculator {
@Override
public
int
calculate(String exp) {
int
arrayInt[] = split(exp,
"-"
);
return
arrayInt[
0
]-arrayInt[
1
];
}
}
1
2
3
4
5
6
7
8
public
class
Multiply
extends
AbstractCalculator
implements
ICalculator {
@Override
public
int
calculate(String exp) {
int
arrayInt[] = split(exp,
"\\*"
);
return
arrayInt[
0
]*arrayInt[
1
];
}
}
简单的测试类:
1
2
3
4
5
6
7
8
9
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
- 13、策略模式(strategy)
- 13、策略模式(strategy)
- 设计模式(13)-策略模式(Strategy)
- 策略(Strategy)模式
- Strategy(策略)模式
- 策略(Strategy)模式
- Strategy(策略模式)
- 策略模式(Strategy)
- 策略模式(Strategy)
- Strategy(策略模式)
- 策略模式(Strategy)
- 策略模式(Strategy)
- 策略(strategy)模式
- 策略模式(strategy)
- 策略(strategy)模式
- 策略模式(Strategy)
- 策略模式(Strategy)
- 策略模式(Strategy)
- 使用Spring Boot开发WEB页面(转载)
- Spring中获取bean的方式
- java 基础问题
- 12、享元模式(Flyweight)
- java中jdbc查询出来的数据转为json数组
- 13、策略模式(strategy)
- 多进程锁、共享内存
- 14、模板方法模式(Template Method)
- Java基础 线程 通信
- Windows 7下Python Web开发环境搭建笔记
- CAS 之3.x版本,单点登录服务搭建(Window)-yellowcong
- 教你用深度学习LSTM网络预测流行音乐趋势(附代码)
- LeetCode 219.Contains Duplicate II
- Linux学习三-管道、重定向、环境变量、vim编辑器