if else 大法不好吗?好;那为什么要干掉 if else ?是的,简单的逻辑用 if else 处理起来很方便,但是如果是比较重要的判断,而且后续需要不停的增加 if 的话,避免代码冗余,也避免影响旧的逻辑判断,建议还是使用一下设计模式
IF ELSE
比如我们现在有个业务逻辑,需要根据订单类型,处理相应的订单逻辑,那么一般我们的代码是这样的,如果情况比较多的话,还会更长。
/**
* if else区分订单类型
*/
private void getOrder(String type) {
if ("normal".equals(type)) {
// "处理普通订单";
} else if ("group".equals(type)) {
// "处理团购订单";
} else if ("promotion".equals(type)) {
// "处理促销订单";
}
}
策略模式+简单工厂模式
/**
* 策略模式+简单工厂模式
*/
@Test
void contextLoads() {
String result = factoryForOrder.getOrderStrategy("normal").handler();
log.info(result);
result = factoryForOrder.getOrderStrategy("group").handler();
log.info(result);
result = factoryForOrder.getOrderStrategy("promotion").handler();
log.info(result);
}
运行结果:
实现
接口
/**
* 不同类型订单处理
*
* @author jason
*/
public interface IOrderService {
String handler();
}
接口实现类
@Component("normal")
public class NormalOrderServiceImpl implements IOrderService {
@Override
public String handler() {
return "处理普通订单";
}
}
@Component("group")
public class GroupOrderServiceImpl implements IOrderService {
@Override
public String handler() {
return "处理团购订单";
}
}
@Component("promotion")
public class PromotionOrderServiceImpl implements IOrderService {
@Override
public String handler() {
return "处理促销订单";
}
}
简单工厂类
import com.example.strategy.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 简单工厂类,通过 Spring注解 @Service 和 @Autowired 实现
*
* @author jason
*/
@Service
public class FactoryForOrder {
@Autowired
private Map<String, IOrderService> strategyMap = new ConcurrentHashMap<>(3);
public IOrderService getOrderStrategy(String component) {
IOrderService iOrderService = strategyMap.get(component);
if (iOrderService == null) {
throw new RuntimeException("no strategy defined");
}
return iOrderService;
}
}