Spring Boot 干掉 if else

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;
	}

}

源码

点击下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值