一、案例
假设需求为,根据类型,处理相对应的操作,优化前有以下代码:
public void operation(String type){
if("add".equals(type)){
//执行加法
}else if("sub".equals(type)){
//执行减法
}
//这里还有很多操作
}
二、方案
1、定义接口
public interface OperationService {
Integer operation(Integer num1, Integer num2);
String getType();
}
2、实现各个逻辑策略实现类
public class AddOperationImpl implements OperationService {
@Override
public Integer operation(Integer num1, Integer num2) {
return num1 + num2;
}
@Override
public String getType() {
return "add";
}
}
public class SubOperationImpl implements OperationService {
@Override
public Integer operation(Integer num1, Integer num2) {
return num1 - num2;
}
@Override
public String getType() {
return "sub";
}
}
3、编写策略工厂类
public class OperationServicesFactory {
private static final Map<String, OperationService> map = new HashMap<>();
static {
map.put("add", new AddOperationImpl());
map.put("sub", new SubOperationImpl());
}
public static OperationService getOperationService(String type) {
return map.get(type);
}
}
4、最终测试
public static void main(String[] args) {
String type="add";
OperationService operation = OperationServicesFactory.getOperationService("type");
System.out.println(operation.operation(1, 2));
}
评论区