用策略模式实现代码 if/else优化
interface Strategy {
void run() throws Exception;
}
class FastStrategy implements Strategy {
@Override
void run() throws Exception {
// 快速执行逻辑
}
}
class NormalStrategy implements Strategy {
@Override
void run() throws Exception {
// 正常执行逻辑
}
}
class SmoothStrategy implements Strategy {
@Override
void run() throws Exception {
// 平滑执行逻辑
}
}
class SlowStrategy implements Strategy {
@Override
void run() throws Exception {
// 慢速执行逻辑
}
}
具体策略对象存放在一个Map中,优化后的实现Strategy strategy = map.get(param);
strategy.run();
用策略模式,写一个策略接口,一个方法,然后每个else就是一个实现类。实现接口中的方法,然后 用map存不同条件new一个实现类。然后get参数返回接口。达到效果
1.